linux/test/socketTestServer.c

99 lines
2.7 KiB
C
Raw Permalink Normal View History

2024-12-17 10:49:27 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT 8001
#define BUFFER_SIZE 1024
#define MAX_CLIENTS 10
// 处理函数示例
void handle_function() {
printf("处理函数被调用!\n");
}
// 客户端处理线程
void *client_handler(void *arg) {
int client_socket = *(int *)arg;
char buffer[BUFFER_SIZE];
int bytes_read;
while ((bytes_read = recv(client_socket, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytes_read] = '\0';
printf("接收到客户端消息: %s\n", buffer);
// 判断是否执行处理函数
if (strcmp(buffer, "execute") == 0) {
handle_function();
send(client_socket, "处理函数已执行\n", strlen("处理函数已执行\n"), 0);
} else {
send(client_socket, "收到消息\n", strlen("收到消息\n"), 0);
}
}
close(client_socket);
printf("客户端断开连接\n");
return NULL;
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
pthread_t thread_pool[MAX_CLIENTS];
int client_count = 0;
// 创建服务器 socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("服务器 socket 创建失败");
exit(EXIT_FAILURE);
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定服务器 socket
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("绑定失败");
close(server_socket);
exit(EXIT_FAILURE);
}
// 开始监听
if (listen(server_socket, MAX_CLIENTS) == -1) {
perror("监听失败");
close(server_socket);
exit(EXIT_FAILURE);
}
printf("服务器已启动,等待客户端连接...\n");
while (1) {
// 接受客户端连接
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_socket == -1) {
perror("接受客户端连接失败");
continue;
}
printf("客户端连接成功,地址: %s\n", inet_ntoa(client_addr.sin_addr));
// 创建线程处理客户端
if (pthread_create(&thread_pool[client_count++], NULL, client_handler, &client_socket) != 0) {
perror("线程创建失败");
}
// 防止线程池溢出
if (client_count >= MAX_CLIENTS) {
client_count = 0;
}
}
close(server_socket);
return 0;
}