我创建了一个TCP服务器进程,一个listenfd描述符,监听端口号4000, 把这个listenfd加入到select函数的监听读集合中,当有新的连接来的时候,那么listenfd就会发生变化,我就可以accept这个新的连接,然后继续监听端口,
但是我测试的客户端为一个的模式发送数据,然后接受服务器的反馈,就只这样不停的循环,运行起来没有问题,从下面的代码看出,这个客户端是个无限循环,但是当我把客户端窗口直接关闭掉,(注意直接关闭点就不执行closesocket(ClientSocket)了), 那么这个一个操作就会是select函数的监听读集合中的listenfd发生变化,导致服务器执行accept,但是这个时候是没有新的连接来的,我不知道为什么出现这种情况,请大侠们解释一下?
WSADATA Ws;
SOCKET ClientSocket;
struct sockaddr_in ServerAddr;
int Ret =
0;
int AddrLen =
0;
HANDLE hThread = NULL;
char SendBuffer[500] = {0};
if(WSAStartup(MAKEWORD(2,2), &Ws) !=
0)
{
cout<<"Init socket failed"<<endl;
return
-1;
}
ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(ClientSocket == INVALID_SOCKET)
{
cout<<"Create socket fadiled"<<endl;
return
-1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.S_un.S_addr = inet_addr(IP_ADDRESS);
ServerAddr.sin_port = htons(PORT);
memset(ServerAddr.sin_zero, 0x00, 8);
Ret = connect(ClientSocket, (struct sockaddr*)&ServerAddr,
sizeof(ServerAddr));
if(Ret == SOCKET_ERROR)
{
cout<<"Connect err"<<endl;
return
-1;
}
else
{
cout<<"Connect success"<<endl;
}
while(true)
{
char RecvBuffer[10000] = {0};
timeval tv;
tv.tv_usec =
0;
tv.tv_sec =
0;
select(0, 0, 0, 0, &tv);
cin.getline(SendBuffer, sizeof(SendBuffer));
Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0);
if(Ret == SOCKET_ERROR)
{
cout<<"Send err"<<endl;
break;
}
Ret = recv(ClientSocket, RecvBuffer, sizeof(RecvBuffer), 0);
{
if(Ret ==
0
|| Ret == SOCKET_ERROR)
{
cout<<"server quit"<<endl;
}
}
cout<<RecvBuffer<<endl;
memset(RecvBuffer, 0, sizeof(RecvBuffer));
}
closesocket(ClientSocket);
WSACleanup();
return
0;
|