一、TCP通信程序完整实现
1.1 服务端实现(多线程版本)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
void* client_handler(void* arg) {
int client_fd = *(int*)arg;
char buffer[BUFFER_SIZE];
// 接收数据(内核:tcp_recvmsg)
ssize_t bytes = recv(client_fd, buffer, BUFFER_SIZE, 0);
if(bytes > 0) {
buffer[bytes] = '\0';
printf("Received: %s\n", buffer);
// 发送响应(内核:tcp_sendmsg)
send(client_fd, "SERVER_ACK", 10, 0);
}
close(client_fd);
free(arg);
return NULL;
}
int main() {