能举个c++upd多线程服务器的例子吗?
时间: 2023-05-11 18:01:56 浏览: 99
一个C++多线程例子
4星 · 用户满意度95%
当然可以,以下是一个简单的 C upd 多线程服务器的例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#define BUF_SIZE 1024
#define MAX_CLIENT 256
void *handle_client(void *arg);
int main(int argc, char *argv[]) {
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_size;
pthread_t t_id;
if (argc != 2) {
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
server_sock = socket(PF_INET, SOCK_DGRAM, 0);
if (server_sock == -1) {
perror("socket() error");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind() error");
exit(1);
}
while (1) {
client_addr_size = sizeof(client_addr);
char buf[BUF_SIZE];
int str_len = recvfrom(server_sock, buf, BUF_SIZE, 0, (struct sockaddr*)&client_addr, &client_addr_size);
if (str_len == -1) {
perror("recvfrom() error");
break;
}
buf[str_len] = 0;
printf("Received from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buf);
pthread_create(&t_id, NULL, handle_client, (void*)&client_sock);
pthread_detach(t_id);
}
close(server_sock);
return 0;
}
void *handle_client(void *arg) {
int client_sock = *((int*)arg);
char buf[BUF_SIZE];
int str_len;
while ((str_len = read(client_sock, buf, BUF_SIZE)) != 0) {
write(client_sock, buf, str_len);
}
close(client_sock);
return NULL;
}
```
这个服务器使用 UDP 协议,可以同时处理多个客户端的请求。当有客户端连接时,服务器会创建一个新的线程来处理该客户端的请求。
阅读全文