【发布时间】:2013-02-06 09:33:38
【问题描述】:
我需要在端口 55005 向服务器发送多个请求(命令)。 我的第一个请求获取过程成功,我也收到了。 但是对于第二个请求,它会给出错误(WSAESHUTDOWN - 错误 10058)。 第一次请求后,我打电话 关机(连接套接字,SD_SEND); 然后只有服务器处理第一个请求并向我发送输出。 现在可以重新打开套接字处理下一个请求了吗?**
关机后如何处理多个请求(ConnectSocket, SD_SEND) ? 提前感谢您的建议。
我发送第一个请求,等待第一个回复。在第一次请求回复后,我可以发送下一个请求。这是业务逻辑要求。我不想为每个请求打开一个新连接。
快照代码从这里开始---------------->
**//This for loop will send multiple request to Servers.**
for(it = CommandList.begin(); it != CommandList.end() ; it++ )
{
//get each command request & send it to server.
std::string sendBuf; // = (*it);
sendBuf= *it;
int length = (int)strlen(sendBuf.c_str());
//----------------------
// Send an initial buffer
iResult = send( ConnectSocket, (char*)sendBuf.c_str(), length, 0 );
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %d\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
wprintf(L"Bytes received: %d\n", iResult);
else if ( iResult == 0 )
wprintf(L"Connection closed\n");
else
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
}
【问题讨论】:
-
当您有更多数据要发送时,为什么要关闭套接字进行发送?这没有任何意义。
-
那你为什么用
strlen来获取std::string的长度? -
我发送第一个请求,等待第一个回复。在第一次请求回复后,我可以发送下一个请求。这是业务逻辑要求。我不想为每个请求打开一个新连接。
-
那又怎样?您还有更多请求要发送,所以不要关闭。就这么简单。你不应该这样做除非你绝对没有更多可以发送。您仍然可以接收数据,所有套接字都是全双工的,即可以同时发送和接收。
-
关闭后必须重新打开。您应该考虑修改协议以包含某种类型的请求结束标记,或包含消息的长度。