1

我正在尝试使用select()UDP 套接字传输创建超时。我想发送intfrom clientto server,等待 300 毫秒,如果我没有收到 ACK,请重新发送数据包。我不确定如何使用超时正确设置它。根据我在网上收集的信息和课堂上的笔记,select应该在接收端使用。

服务器上的客户端来回发送数字 1-100。我有一个单独的router模拟代码,可以随机丢弃数据包

这是我为客户端提供的代码

int sent = 1;
int received = 1;

    for (int i = 0; i < 100; i++)
    {
        string sent1 = to_string(sent);
        char const *pchar = sent1.c_str();
        if(!sendto(s, pchar, sizeof(pchar), 0, (struct  sockaddr*) &sa_in, sizeof(sa_in)))
            cout << "send NOT successful\n";
        else
        {
            cout << "Client sent " << sent << endl;
            sent++;
        }
        // receive
        fd_set readfds; //fd_set is a type
        FD_ZERO(&readfds); //initialize 
        FD_SET(s, &readfds); //put the socket in the set

        if(!(outfds = select (1 , &readfds, NULL, NULL, & timeouts))) 
            break;
        if (outfds == 1) //receive frame
        {
            if (!recvfrom(s, buffer2, sizeof(buffer2), 0, (struct sockaddr*) &client, &client_length))
                cout << "receive NOT successful\n";
            else
            {
                received = atoi(buffer2);
                cout << "Client received " << received << endl;
                received++;
            }
        }
    }

接收端的代码是相同的,只是它是相反的:先接收,然后发送

我的代码根本没有利用超时。这基本上是我想要做的:

send packet(N)
    if (timeout)
        resend packet(N)
    else
        send packet(N+1)
4

1 回答 1

2

如果接收者超时,它需要告诉发送者,否则告诉发送者。换句话说,您必须实现基于 NACK 的协议或基于 ACK 的协议。

于 2013-11-04T05:01:35.703 回答