【发布时间】:2013-11-14 17:18:47
【问题描述】:
我正在尝试使用 select() 为 UDP 套接字传输创建超时。我想从client 向server 发送一个int,等待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)
【问题讨论】:
-
Udp 代表 不可靠 数据报协议。它不执行确认或重新发送。您必须自己实施。这里的发送超时是为了将数据包推送到线路或网络堆栈上丢弃它。
标签: c++ sockets udp timeout packet