如何在C添加延迟澡堂和recvfrom在UDP客户端/服务器 [英] How to add delay to sento and recvfrom in UDP client/server in C

查看:135
本文介绍了如何在C添加延迟澡堂和recvfrom在UDP客户端/服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关在学校规划项目,我们有使用TCP协议,然后UDP协议来设计一个基本的客户机/服务器设置。我已经得到了使用TCP从C套接字库的read()和write()工作。我现在需要创造一个可靠的UDP制度。例如:

For a programming project in school we have to design a basic client/server setup using tcp protocol and then udp protocol. I already got the TCP working using read() and write() from the C Socket library. I now need to create a "reliable UDP" system. For instance:

ACK,当服务器接收要发送的长度信息,将等待长达500毫秒为字节数。如果它收到正确的字节数,它会与含有字符的字符串响应(一为确认共同缩写)。如果它不超时期末收到正确的字节数,服务器将放弃​​和默默退出。

"When the server receives the length message it will wait up to 500 milliseconds for that number of bytes to be sent. If it receives the correct number of bytes, it will respond with a string containing the characters "ACK" (a common abbreviation for an acknowledgement). If it does not receive the correct number of bytes by the end of the timeout period, the server will give up and silently exit."

我有SENDTO()和recvfrom()函数成立,但我不知道该怎么办了超时功能,使其只能等待500毫秒要发送第二味精。我也有后来做在客户端如果没有收到确认,然后重新发送长度味精味精+几次。怎么办怎么办超时?

I have the sendto() and recvfrom() functions set up, but I am not sure how to do the timeout feature so that it only waits 500ms for the second msg to be sent. I also have to do it later on the client side if it doesn't receive the "ACK" and resend the length msg + msg a few times. How can do I do the timeout?

推荐答案

添加以下功能在你的程序,并使用它,而不是直接使用recvfrom函数的。

Add the following function in your program and use it instead of using the recvfrom function directly.

下面functiong具有recvfrom函数的相同的输入参数中+最后一个超时输入参数

the following functiong has the same input parameter of recvfrom function + a timeout input parameter in the last

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>

int timeout_recvfrom (int sock, char *buf, int *length, struct sockaddr_in *connection, int timeoutinseconds)
{
    fd_set socks;
    struct timeval t;
    FD_ZERO(&socks);
    FD_SET(sock, &socks);
    t.tv_sec = timeoutinseconds;
    if (select(sock + 1, &socks, NULL, NULL, &t) &&
        recvfrom(sock, buf, *length, 0, (struct sockaddr *)connection, length)!=-1)
        {
        return 1;
        }
    else
        return 0;
}

这篇关于如何在C添加延迟澡堂和recvfrom在UDP客户端/服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆