如图:四次挥手,关闭函数,作用:
#if 0//-----2--TCP并发服务器--------//
//----- ----------//
int main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd<0)
{
printf("socket error\n");
return 0;
}
//设置端口复用
int yes=1;
setsockopt(sockfd, SOL_SOCKET,SO_REUSEADDR,&yes, sizeof(yes));
struct sockaddr_in my_addr;
bzero(&my_addr, sizeof(my_addr));
//服务器绑定
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9000);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
//监听客户
listen(sockfd, 20);
//保存链接的客户端的
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
//保存服务器接收到的信息
char buf[128] = "";
//与客户端通信的临时套接字
int sockfd_new;
//保存客户端的点分十进制
char ip[16] = "";
pid_t pid;
while(1)
{
sleep(1);
bzero(&cli_addr, sizeof(cli_addr));
sockfd_new = accept(sockfd,(struct sockaddr *)&cli_addr, &len );
pid = fork();
if(pid < 0)
{
return;
}
else if(pid == 0)
{
close(sockfd);
inet_ntop(AF_INET, &cli_addr.sin_addr.s_addr, ip, 16);
printf("子进程中 IP %s 已连接服务器\n",ip);
while(1)
{
memset(buf, 0, sizeof(buf));
recv(sockfd_new, buf, sizeof(buf), 0);
printf("收到--buf----%s \n",buf);
send(sockfd_new, buf, strlen(buf), 0);
if(strncmp(buf, "bye", 3) == 0 || strlen(buf) == 0)
{
break;
}
}
printf("子进程中 IP %s 已断开服务器\n",ip);
close(sockfd_new);
exit(0);
}
else
{
close(sockfd_new);
//父子进程中的内容一样的,父进程同样需要关闭,结束的临时套接字
//然后在返回监听
//wait(NULL);
}
}
close(sockfd);
return 0;
}
#endif