进程实现并发tcp通信

This commit is contained in:
flykhan 2023-09-07 10:55:34 +08:00
parent 4db309ba54
commit e982d860bc
1 changed files with 92 additions and 0 deletions

92
day4/echo1.c Normal file
View File

@ -0,0 +1,92 @@
// 进程实现并发tcp通信
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
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;
}