我正在为个人学习目的编写一个MUD服务器,我很高兴地设法将套接字的东西打包成几个类,并且一切似乎都正常工作;服务器侦听并接受连接,当前从客户端获取文本并将其发送回。
问题是我不太确定如何处理返回 WSAEWOULDBLOCK 或有效套接字以外的其他内容的 accept() 调用。我是否只是将新套接字重置为 0 并返回,可能会出现一条错误消息,说明发生了不好的事情?这就是我现在正在做的事情,如果它发生 20 次,我将关闭服务器。
void MUDControlSocket::Poll()
{
// create a new connection here
timeval timeout;
FD_ZERO(&ReadSet);
FD_ZERO(&WriteSet);
FD_ZERO(&ExceptionSet);
TopSocket = GetSocket();
NewSocket = 0;
FD_SET( GetSocket(), &ReadSet );
if( SocketList.size() > 0 )
{
for( sockIter iter = SocketList.begin(); iter != SocketList.end(); ++iter )
{
FD_SET((*iter)->GetSocket(), &ReadSet);
FD_SET((*iter)->GetSocket(), &WriteSet);
FD_SET((*iter)->GetSocket(), &ExceptionSet);
TopSocket = (*iter)->GetSocket();
}
}
if( select( TopSocket+1, &ReadSet, &WriteSet, &ExceptionSet, &timeout ) == SOCKET_ERROR )
{
cout << "Error on select() call: " << SocketErrorType(WSAGetLastError()) << endl;
delete this;
exit(EXIT_FAILURE);
}
// as long as everything is working correctly, this if block should always be entered UNLESS a new connection is accepted
if( (NewSocket = accept(GetSocket(), NULL, NULL) ) == INVALID_SOCKET )
{
if( WSAGetLastError() == WSAEWOULDBLOCK ) // it's not an actual problem. just nothing to connect to yet
return;
NewSocket = 0;
static int count = 0;
cout << "Error on accepting new connection: " << SocketErrorType(WSAGetLastError()) << endl;
if( ++count >= 20 )
done = true;
return;
}
SocketList.push_back(new MUDSocket(NewSocket)); // only happens if accept DOES NOT return a value of INVALID_SOCKET i.e. a new connection was accepted
TopSocket = NewSocket;
NewSocket = 0;
}
TopSocket 和 NewSocket 属于 SOCKET 类型,并在文件范围内声明。SocketList 是 MUDSocket* 的 std::list,而 MUDControlSocket 作为单例从 MUDSocket 派生。
如果您需要更多信息,请告诉我,并感谢您的帮助。