2012-06-23 51 views
0

我有一个客户端/服务器应用程序。 客户端向服务器发送问题并收到答案。套接字 - 从服务器接收答案后发送更多数据

这很好 - 但是当我试图再次使用相同的套接字来发送另一个问题(没有关闭套接字 - 收到答案后)服务器没有得到第二个问题。

这里的发送和接收答案的代码(这应该在一些排序的循环工作):

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); 
+0

你在客户端有什么错误吗?尝试在您的头文件中添加“Connection:Keep-Alive”(请参阅​​http://en.wikipedia.org/wiki/HTTP_persistent_connection) –

+0

接收循环内的断言失败(因为它没有从服务器获得响应 - >因为服务器没有发送答案 - >因为它没有得到客户端的第二个问题) – YogevSitton

+0

找出错误是什么。 IIRC在Windows上是'GetLastError()'。另外,响应可能会比256字节更短或更大,你如何处理? –

回答

0

有了这个代码是不可能的,你都不能发送的第二个问题,你永远不可能离开读取回复的循环(除非因为你的偏移量溢出缓冲区,或者当对方关闭连接而导致分段冲突,在这种情况下你不能发送,他也不能接收)。

而只是断言没有错误是不够的。如果您遇到错误,您需要查看相应的内容并做出反应。至少你需要打印它。

相关问题