一、问题描述
TCP编程学习中,当打开tcp_server后,同时打开一个tcp_client不运行。再打开一个tcp_client发送数据后。
tcp_server没有响应,因为tcp_server建立和第一个tcp_client的连接后,一直在等待它的数据(阻塞状态)。
为了解决这个问题,我们需要创建子进程来接受数据,而父进程只要一直建立连接就行了。这样就能不断的处理数据了。
二、代码改写
tcp_server->tcp_server_fork.c:
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
#include <stdio.h>
-
#include <strings.h>
-
#include <arpa/inet.h>
-
-
#define portnum 3333
-
-
int main()
-
{
-
int sockfd;
-
int new_fd;
-
struct sockaddr_in server_addr;
-
struct sockaddr_in client_addr;
-
char buffer[128];
-
int nbyte = 0;
-
int sin_size;
-
pid_t pid;
-
-
/*1.创建socket*/
-
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
-
{
-
printf("create socket error!\n");
-
exit(1);
-
}
-
-
/*2.1设置要绑定的地址*/
-
bzero(&server_addr, sizeof(struct sockaddr_in));
-
server_addr.sin_family = AF_INET;
-
server_addr.sin_port = htons(portnum);
-
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
/*2.2.绑定地址*/
-
bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
-
-
/*3.监听端口*/
-
listen(sockfd, 5);
-
-
while(1)
-
{
-
/*4.等待链接*/
-
sin_size = sizeof(struct sockaddr);
-
new_fd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
-
if(new_fd == -1)
-
{
-
printf("accept socket failed\n");
-
exit(1);
-
}
-
-
printf("server get connection form %s\n", inet_ntoa(client_addr.sin_addr));
-
/*由子进程来处理数据通讯*/
-
if(pid = fork() == 0)
-
{
-
/*5.接收数据*/
-
nbyte = recv(new_fd, buffer, 128, 0);
-
buffer[nbyte] = '\0';
-
printf("server received : %s\n",buffer);
-
-
/*6.结束链接*/
-
close(new_fd);
-
close(sockfd);
-
exit(0);
-
}
-
else if(pid < 0)
-
{
-
printf("fork error!\n");
-
}
-
}
-
-
close(sockfd);
-
-
return 0;
-
}
阅读(680) | 评论(0) | 转发(0) |