c++ udp 服务端 多线程代码
时间: 2023-09-14 20:12:05 浏览: 117
很好,我可以为您提供C语言编写的UDP服务端多线程代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAXLINE 1024
#define SERV_PORT 8888
struct s_info {
struct sockaddr_in cliaddr;
int connfd;
};
void* do_work(void* arg);
int main(int argc, char** argv) {
int listenfd, connfd;
pthread_t tid;
struct sockaddr_in servaddr, cliaddr;
socklen_t len = sizeof(cliaddr);
char buf[MAXLINE];
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
printf("Accepting connections ...\n");
while (1) {
memset(buf, 0, sizeof(buf));
int n = recvfrom(listenfd, buf, MAXLINE, 0, (struct sockaddr*)&cliaddr, &len);
printf("Received from %s at PORT %d\n",
inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
struct s_info* ts = (struct s_info*)malloc(sizeof(struct s_info));
ts->cliaddr = cliaddr;
ts->connfd = listenfd;
pthread_create(&tid, NULL, do_work, (void*)ts);
}
return 0;
}
void* do_work(void* arg) {
pthread_t tid = pthread_self();
struct s_info* ts = (struct s_info*)arg;
char buf[MAXLINE];
char str[INET_ADDRSTRLEN];
memset(buf, 0, sizeof(buf));
inet_ntop(AF_INET, &(*ts).cliaddr.sin_addr, str, sizeof(str));
printf("Thread with ID %ld servicing %s:%d\n", tid, str, ntohs((*ts).cliaddr.sin_port));
while (1) {
int n = recvfrom((*ts).connfd, buf, MAXLINE, 0, (struct sockaddr*)&(*ts).cliaddr, &len);
if (n == 0) {
printf("The client %s:%d has closed the connection\n", str, ntohs((*ts).cliaddr.sin_port));
break;
}
printf("Received from %s at PORT %d: %s\n",
inet_ntoa((*ts).cliaddr.sin_addr), ntohs((*ts).cliaddr.sin_port), buf);
sendto((*ts).connfd, buf, n, 0, (struct sockaddr*)&(*ts).cliaddr, len);
}
close((*ts).connfd);
free(ts);
pthread_exit(NULL);
}
```
此代码实现了一个简单的UDP服务端,它能够接收来自任意IP地址和端口号的UDP数据报文,并把接收到的数据原封不动地发回给客户端。此服务端是一个基于多线程的实现,可以同时服务多个客户端。每个客户端都分配一个线程来处理其请求。
阅读全文