0

我的作业是编写让客户端到服务器延迟估计的函数。我需要从客户端发送“几点了?”的 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;
        }
4

2 回答 2

0

您是否尝试过切换到 recvfrom?由于您使用的是 sendto,因此它的镜像功能应该更有意义。

此外,如果您在处理单个接收之前发送 50 个请求,您的延迟将不会有任何好处。您的平均值应根据多个单个发送/接收对计算

于 2012-04-30T20:54:52.523 回答
-1

定义两个整数变量(开始,结束)在处理从服务器发送的for循环中的错误后添加此代码

            recvBuff[bytesRecv] = '\0'; //for handling null terminated to the answer

            if (i == 0)
            {
                start = atoi(recvBuff);
            }
            if(i == 50){
            end = atoi(recvBuff);
            }


        cout << endl << "Time Client: Delay Estimation:       " << (end - start) / 50<< " ms " << endl;
于 2020-08-18T09:02:40.153 回答