Linux 实现TCP并发服务器
并发服务器 实现多个进程能同时访问服务器
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUF_SIZE 1024
void handle_client(int client_fd) {
char buf[BUF_SIZE];
ssize_t recv_len;
while ((recv_len = recv(client_fd, buf, BUF_SIZE, 0)) > 0) {
buf[recv_len] = '\0'; // 确保字符串以空字符结尾
printf("收到消息:%s\n", buf);
// 回显收到的消息
send(client_fd, buf, recv_len, 0);
}
if (recv_len == 0) {
printf("客户端关闭连接。\n");
} else {
perror("recv failed");
}
close(client_fd);
exit(0);
}
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// 创建套接字
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket failed");
exit(1);
}
// 允许地址重用
int on = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
perror("setsockopt failed");
exit(1);
}
// 绑定地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind failed");
exit(1);
}
// 监听连接请求
if (listen(server_fd, 10) == -1) {
perror("listen failed");
exit(1);
}
printf("服务器启动,监听端口 %d...\n", PORT);
while (1) {
// 接受连接请求
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_fd == -1) {
perror("accept failed");
continue;
}
printf("客户端连接:%s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
// 创建子进程处理客户端请求
if (fork() == 0) {
// 子进程关闭服务器套接字
close(server_fd);
handle_client(client_fd);
exit(0);
} else {
// 父进程关闭客户端套接字
close(client_fd);
}
}
// 关闭服务器套接字
close(server_fd);
return 0;
}