From e982d860bc5c04407f40f9890980fed6d750fdc5 Mon Sep 17 00:00:00 2001 From: flykhan Date: Thu, 7 Sep 2023 10:55:34 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E7=A8=8B=E5=AE=9E=E7=8E=B0=E5=B9=B6?= =?UTF-8?q?=E5=8F=91tcp=E9=80=9A=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day4/echo1.c | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 day4/echo1.c diff --git a/day4/echo1.c b/day4/echo1.c new file mode 100644 index 0000000..9c8ff04 --- /dev/null +++ b/day4/echo1.c @@ -0,0 +1,92 @@ +// 进程实现并发tcp通信 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char const *argv[]) +{ + // 1. 创建 socket + int sock_fd = socket(AF_INET, SOCK_STREAM, 0); + if (sock_fd < 0) + { + perror("socket"); + return 1; + } + + // 2. bind + struct sockaddr_in server_addr; + bzero(&server_addr, sizeof(server_addr)); + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(atoi(argv[1])); + server_addr.sin_addr.s_addr = htonl(INADDR_ANY); + + int flag = bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)); + if (flag != 0) + { + perror("bind"); + close(sock_fd); + return 1; + } + + // 3. 创建监听队列 + listen(sock_fd, 100); + + // 4. 开始接收客户端的连接(并发接收多个客户端) + while (1) + { + struct sockaddr_in client_addr; + bzero(&client_addr, sizeof(client_addr)); + socklen_t client_addr_len = sizeof(client_addr); + + int client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len); + + char clinet_ip[INET_ADDRSTRLEN] = ""; + inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, clinet_ip, INET_ADDRSTRLEN); + printf("%s 连接成功\n", clinet_ip); + + // 创建进程实现并发通信 + if (fork() == 0) // 子进程的作用域限制此范围 + { + close(sock_fd); // 关闭父进程的socket文件描述符 + + while (1) + { + char buf[128] = ""; + ssize_t len = recv(client_fd, buf, 128, 0); + if (len > 0) + { + int i = 0; + while (buf[i]) + { + buf[i] = toupper(buf[i]); + i++; + } + + send(client_fd, buf, len, 0); + + if (strncmp(buf, "BYE", 3) == 0) + { + break; + } + } + } + + close(client_fd); + printf("%s 关闭连接\n", clinet_ip); + _exit(0); // 子进程完成后,自动关闭本子进程 + } + } + + // 主进程的范畴 + close(sock_fd); + + return 0; +}