我正在編寫一個MUD服務器用於個人學習的目的,我愉快地設法將套接字填充到幾個類中,並且一切似乎都正常工作;服務器偵聽並接受連接,並且當前從客戶端獲取文本並將其發回。關於處理不好的電話接受()
事情是我不太確定如何調用accept(),它返回WSAEWOULDBLOCK或有效套接字以外的內容。我是否只是將新套接字重置爲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派生的。
讓我知道你是否需要更多的信息,並感謝您的任何幫助。
感謝您的信息。 – 2011-03-30 18:01:47