UDP持续收发的C代码
时间: 2024-11-03 12:22:14 浏览: 3
UDP(User Datagram Protocol)是一种无连接的数据报协议,适用于对实时性和低延迟有较高需求的应用,如网络游戏、在线聊天等。下面是一个简单的UDP客户端和服务器的C语言示例,展示了如何持续收发数据:
```c
// 客户端发送部分
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 12345
int main() {
struct sockaddr_in server_address;
int client_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (client_socket == -1) {
perror("Failed to create socket");
return 1;
}
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
inet_pton(AF_INET, "localhost", &server_address.sin_addr); // 本地IP
char message[] = "Hello from client";
while (1) {
sendto(client_socket, message, strlen(message), 0,
(struct sockaddr *)&server_address, sizeof(server_address));
printf("Message sent.\n");
sleep(1); // 持续发送,间隔1秒
}
close(client_socket);
return 0;
}
// 服务器接收部分
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#define BUFFER_SIZE 256
void receive_data(int server_socket) {
struct sockaddr_in client_address;
socklen_t address_length = sizeof(client_address);
char buffer[BUFFER_SIZE];
while (1) {
ssize_t bytes_received = recvfrom(server_socket, buffer, BUFFER_SIZE, 0,
(struct sockaddr *)&client_address, &address_length);
if (bytes_received > 0) {
printf("Received message from %s: %.*s\n",
inet_ntoa(client_address.sin_addr),
(int)bytes_received, buffer);
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
} else {
perror("Error receiving data");
}
}
}
int main() {
int server_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (server_socket == -1) {
perror("Failed to create socket");
return 1;
}
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
server_address.sin_addr.s_addr = htonl(INADDR_ANY); // 静态绑定到所有接口
bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address));
printf("Server started on port %d.\n", ntohs(PORT));
// 异步处理接收请求
pid_t child_pid = fork();
if (child_pid == 0) { // 子进程
receive_data(server_socket);
exit(0);
} else if (child_pid < 0) {
perror("Fork failed");
exit(1);
}
receive_data(server_socket); // 主进程继续接收其他请求
close(server_socket);
return 0;
}
```
在这个例子中,客户端持续向服务器发送消息,而服务器在独立的子进程中监听并打印接收到的消息。
阅读全文