关于一个socket在阻塞模式下是否还可以使用的实验

想到一个socket在多线程模式下,是否可以同时使用的问题,比如socket A阻塞在recv,而别的线程用socket A send是否能成功,下面上实验代码

 void thread_socket(int socket)
{
Sleep();
int error = send(socket, "asd", strlen("asd"), ); char recData[] = {};
//setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&time, sizeof(int));
int ret = recv(socket, recData, , );
getchar();
}
int main()
{
unsigned short port = ; char ch1[] = { ,,, };
memcpy(ch1, &port, );
string s1;
s1= string(ch1, );
string s("", );
unsigned short unsi = ;
char *ch = ((char*)&unsi); char ccc[] = {};
unsigned short t = *((unsigned short *)(ch)); WORD sockVersion = MAKEWORD(, );
WSADATA data;
if (WSAStartup(sockVersion, &data) != )
{
return ;
}
sockaddr_in serAddr;
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons();
inet_pton(AF_INET, "127.0.0.1", &serAddr.sin_addr); while (true)
{
SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sclient == INVALID_SOCKET)
{
printf("invalid socket!");
return ;
}
if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
{ //连接失败
printf("connect error !");
closesocket(sclient);
return ;
}
send(sclient, "asd", strlen("asd"), );
char recData[];
int nNetTimeout = ;
/*setsockopt(sclient, SOL_SOCKET, SO_RCVTIMEO, (char *)&nNetTimeout, sizeof(int));*/ int opt_val;
socklen_t opt_len = sizeof(opt_val);
//getsockopt(sclient, IPPROTO_TCP, SO_SNDBUF, (char *)&opt_val, (socklen_t *)&opt_len); std::thread t(thread_socket, sclient);
int i = ;
while (i--)
{
int ret = recv(sclient, recData, , );
if (ret > ) {
recData[ret] = 0x00;
printf(recData);
}
}
closesocket(sclient);
}
WSACleanup();
return ;
}

经过实验发现,socket A阻塞在recv,而别的线程用socket A send是可以成功的。

还有个发现,当一个socket被多出recv时,内核返回时会回调最先调用recv的地方

上一篇:error-2015-9-9


下一篇:Spring入门(3)-Spring命名空间与Bean作用域