我的作业是编写让客户端到服务器延迟估计的函数。我需要从客户端发送“几点了?”的 50 个请求。并且比从服务器接收 50 个响应(通过 getTickCount()) - 并且比计算平均值。问题是由于某种原因,第二个 recv 函数崩溃了,我不知道为什么。这是我的代码的一部分(来自我的客户):
WSAData wsaData;
if (NO_ERROR != WSAStartup(MAKEWORD(2,2), &wsaData))
{
cout<<"Time Client: Error at WSAStartup()\n";
}
SOCKET connSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (INVALID_SOCKET == connSocket)
{
cout<<"Time Client: Error at socket(): "<<WSAGetLastError()<<endl;
WSACleanup();
return;
}
sockaddr_in server;
sockaddr serverr;
int server_len = sizeof(server);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(TIME_PORT);
int bytesSent = 0;
int bytesRecv = 0;
string sendBuff;
char recvBuff[255];
for (i=0 ; i<50;++i)
{
bytesSent = sendto(connSocket,sendBuff.c_str() , (int)strlen(sendBuff.c_str()), 0, (const sockaddr *)&server, sizeof(server));
if (SOCKET_ERROR == bytesSent)
{
cout<<"Time Client: Error at sendto(): "<<WSAGetLastError()<<endl;
closesocket(connSocket);
WSACleanup();
return;
}
}
for (i=0 ; i<50;++i)
{
bytesRecv = recv(connSocket, recvBuff, 255, 0);
if (SOCKET_ERROR == bytesRecv)
{
cout<<"Time Client: Error at recv(): "<<WSAGetLastError()<<endl;
closesocket(connSocket);
WSACleanup();
return;
}