UDP 多线程 相互 守候 服务 C 源代码
时间: 2024-12-25 07:25:09 浏览: 5
UDP (User Datagram Protocol) 是一种无连接的传输层协议,它并不保证数据包的顺序、可靠性或及时到达。在多线程环境中,如果要在UDP服务中实现相互守候(即客户端等待服务器响应或服务器等待客户端请求),通常需要结合多路复用(Multiplexing)技术来处理并发连接。
下面是一个简化的C语言示例,展示了使用多线程在一个简单的UDP服务器上接收客户端消息,并对每个客户端发送回应的基本框架:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#define PORT 12345
void* client_thread(void* arg) {
int client_sock = *(int*)arg;
char buffer[1024];
while (1) {
ssize_t bytes_received = recvfrom(client_sock, buffer, sizeof(buffer), 0, NULL, NULL);
if (bytes_received > 0) {
printf("Received from client: %s\n", buffer);
sendto(client_sock, "Server received your message.", strlen("Server received your message."), 0, (struct sockaddr*)&client_addr, bytes_received); // 发送回应
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
close(client_sock);
break;
} else {
perror("recvfrom failed");
break;
}
}
pthread_exit(NULL);
}
int main() {
int server_sock, one = 1;
struct addrinfo hints, *res, *ptr;
char address[] = "0.0.0.0";
const char* service = "12345";
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Allow IPv4 and IPv6
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(address, service, &hints, &res);
server_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
bind(server_sock, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
printf("Server started on port %d\n", ntohs(server_sock));
for (ptr = res; ptr != NULL; ptr = ptr->ai_next) {
pthread_create(&thread_id, NULL, client_thread, (void*)&server_sock);
}
// Main thread will receive incoming connections
while (1) {
socklen_t len = sizeof(struct sockaddr_in);
ssize_t bytes_received = recvfrom(server_sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_addr, &len);
if (bytes_received > 0) {
printf("New connection: %s:%d\n", inet_ntoa(((struct sockaddr_in*)&client_addr)->sin_addr), ntohs(((struct sockaddr_in*)&client_addr)->sin_port));
pthread_create(&thread_id, NULL, client_thread, (void*)&server_sock);
} else {
perror("recvfrom failed");
break;
}
}
return 0;
}
阅读全文