2013-11-04 78 views
1

我正在尝试使用select()为UDP套接字传输创建超时。我想发送intclientserver,等待300ms,如果我没有收到ACK,请重新发送数据包。我不确定如何在超时时间内正确设置它。从我在线收集的内容以及我在课堂上收到的笔记中,应该在接收端使用select丢失数据包超时(UDP)

服务器上的客户端来回发送数字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) 
+0

Udp表示*不可靠*数据报协议。它不会执行或重新发送。你必须自己实现。这里的发送超时是将数据包推送到有线或网络堆栈上丢弃它。 – kfsone

回答

2

如果接收端收到超时它需要转告寄件人,否则转告寄件人。换句话说,您必须实现基于NACK的协议或基于ACK的协议。