我正在尝试使用select()
为UDP套接字传输创建超时。我想从int
向client
发送server
,等待300毫秒,如果我没有收到确认,请重新发送数据包。我不确定如何使用超时正确设置它。从我在网上收集的内容和课堂上的笔记中,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)
答案 0 :(得分:2)
如果接收方获得超时,则需要告知发送方,否则不告诉发送方。换句话说,您必须实现基于NACK的协议或基于ACK的协议。