【发布时间】:2012-06-25 17:35:54
【问题描述】:
我有一个客户端/服务器应用程序。 客户端向服务器发送问题并接收答案。
这很好用 - 但是当我尝试再次使用同一个套接字发送另一个问题时(不关闭套接字 - 在收到答案后),服务器没有收到第二个问题。
这是发送和接收答案的代码(这应该在某种循环中工作):
char* buf = "GET /count.htm HTTP/1.1\r\nHost: 127.0.0.1:666\r\nAccept: text/html,application/xhtml+xml\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/5.0\r\n\r\n";
int nBytesToSend= strlen(buf);
int iPos=0;
while(nBytesToSend)
{
int nSent=send(hClientSocket,buf,nBytesToSend,0);
assert(nSent!=SOCKET_ERROR);
nBytesToSend-=nSent;
iPos+=nSent;
}
//prepare buffer for incoming data
char serverBuff[256];
int nLeft=sizeof(serverBuff);
iPos=0;
do //loop till there are no more data
{
int nNumBytes=recv(hClientSocket,serverBuff+iPos,nLeft,0);
//check if cleint closed connection
if(!nNumBytes)
break;
assert(nNumBytes!=SOCKET_ERROR);
//update free space and pointer to next byte
nLeft-=nNumBytes;
iPos+=nNumBytes;
}while(1);
【问题讨论】:
-
您在客户端收到任何错误吗?尝试将
Connection: Keep-Alive添加到您的标题中(请参阅en.wikipedia.org/wiki/HTTP_persistent_connection) -
接收循环内的断言失败(因为它没有得到服务器的响应 -> 因为服务器没有发送答案 -> 因为它没有从客户)
-
找出错误所在。 Windows 上的 IIRC 是
GetLastError()。此外,响应可能比 256 字节更短或更大,您如何处理? -
错误是客户端从服务器没有得到任何东西。断言(nNumBytes!=SOCKET_ERROR);失败
-
这可能有多种原因。
GetLastError()返回了一个特定的错误代码,然后您将其传递给FormatMessage()或在此处查找 msdn.microsoft.com/en-us/library/ms681381(v=vs.85).aspx。这会告诉你到底出了什么问题。
标签: windows winapi sockets winsock