linux c语言 udp收到消息0x0后发送消息超时5秒总超时20秒未收到0x02重发
时间: 2023-12-10 20:42:41 浏览: 128
你可以使用 `select()` 函数来实现超时等待和重发。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/select.h>
#define BUF_SIZE 1024
#define SERVER_PORT 8888
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
char buf[BUF_SIZE];
int ret, recv_len;
fd_set read_fds;
struct timeval timeout;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (ret < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
while (1) {
FD_ZERO(&read_fds);
FD_SET(sockfd, &read_fds);
timeout.tv_sec = 5;
timeout.tv_usec = 0;
ret = select(sockfd + 1, &read_fds, NULL, NULL, &timeout);
if (ret < 0) {
if (errno == EINTR) {
continue;
}
perror("select");
exit(EXIT_FAILURE);
} else if (ret == 0) {
// timeout, send again
printf("timeout, send again\n");
ret = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&client_addr, addr_len);
if (ret < 0) {
perror("sendto");
exit(EXIT_FAILURE);
}
} else {
// receive data
recv_len = recvfrom(sockfd, buf, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len);
if (recv_len < 0) {
perror("recvfrom");
exit(EXIT_FAILURE);
}
buf[recv_len] = '\0';
printf("received data: %s\n", buf);
if (buf[0] == 0x02) {
// received 0x02, break the loop
break;
}
}
}
close(sockfd);
return 0;
}
```
在上面的代码中,我们使用 `select()` 函数来等待数据的到来,如果超时了就重发。如果收到了期望的数据,我们就跳出循环。注意,在重发时我们需要保存客户端的地址信息,以便重新发送数据。
当然,这只是一个示例代码,你需要根据你自己的需求进行修改。
阅读全文