#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <pthread.h>
#define PORT 8080
#define MAX_CLIENTS 5
// 多进程服务器
void handle_client_process(int client_socket) {
char buffer[1024] = {0};
ssize_t valread;
valread = read(client_socket, buffer, 1024);
printf("Message from client: %s\n", buffer);
write(client_socket, "Server message: I got your message", strlen("Server message: I got your message"));
close(client_socket);
}
void start_multi_process_server() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
int pid = fork();
if (pid == 0) {
close(server_fd);
handle_client_process(new_socket);
exit(0);
} else if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
close(new_socket);
}
}
// 多线程服务器
void *handle_client_thread(void *arg) {
int client_socket = *((int *)arg);
char buffer[1024] = {0};
ssize_t valread;
valread = read(client_socket, buffer, 1024);
printf("Message from client: %s\n", buffer);
write(client_socket, "Server message: I got your message", strlen("Server message: I got your message"));
close(client_socket);
pthread_exit(NULL);
}
void start_multi_thread_server() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
pthread_t thread_id;
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
if (pthread_create(&thread_id, NULL, handle_client_thread, (void *)&new_socket) < 0) {
perror("could not create thread");
exit(EXIT_FAILURE);
}
}
}
int main() {
start_multi_process_server(); // 启动多进程服务器
// start_multi_thread_server(); // 启动多线程服务器
return 0;
}
【day8作业】
最新推荐文章于 2024-08-16 15:51:32 发布