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 ip[16] = "";
inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip, 16);
printf("%s 连接成功\n", ip);
// 创建进程实现并发通信
if (fork() == 0)
{ // 子进程的作用域限制此范围
close(sock_fd);
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", ip);
_exit(0);
}
}
// 主进程的范畴