帮我用c语言写一个并发服务器并用中文注释
时间: 2023-03-01 17:00:08 浏览: 110
好的,以下是一个简单的并发服务器代码,带有中文注释:
```
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#define PORT 8080
#define MAX_CLIENTS 5
#define BUFFER_SIZE 1024
// 定义每个客户端的结构体
typedef struct {
int sock;
struct sockaddr_in address;
} client_t;
// 存储客户端的数组
client_t clients[MAX_CLIENTS];
// 定义线程的处理函数
void *handle_client(void *arg) {
client_t *client = (client_t *)arg;
// 接收客户端的请求
char buffer[BUFFER_SIZE];
int read_size = recv(client->sock, buffer, BUFFER_SIZE, 0);
buffer[read_size] = '\0';
printf("Received: %s\n", buffer);
// 向客户端发送响应
char *message = "Hello from the server";
send(client->sock, message, strlen(message), 0);
printf("Sent: %s\n", message);
// 关闭客户端的套接字
close(client->sock);
return 0;
}
int main() {
int server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == -1) {
printf("Could not create socket");
return 1;
}
// 设置服务器地址
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
// 绑定服务器地址到套接字
if (bind(server_sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
printf("Bind failed");
return 1;
}
// 监听服务器套接字
listen(server_sock, MAX_CLIENTS);
printf("Listening on port %d...\n", PORT);
// 接收客户端的连接
int client_count = 0;
while (1) {
阅读全文