#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#define IP "192.168.124.118"
#define PORT 5050
int do_cli_msg(int newfd,struct sockaddr_in cin);
void recycle_zombine(int sig)//17号处理函数
{
while(waitpid(-1,NULL,WNOHANG) > 0);
}
int main(int argc, const char *argv[])
{
//捕获17号SIGCHLD
if(signal(17,recycle_zombine) == SIG_ERR)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("signal");
return -1;
}
//创建流式套接字文件
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("socket");
return -1;
}
printf("创建流式套接字文件成功\n");
//填充服务器的地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
//允许端口号被快速重复使用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
fprintf(stderr, "line:%d ", __LINE__);
perror("setsockopt");
return -1;
}
//绑定服务器自身的地址信息
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("bind");
return -1;
}
printf("bind success __%d__\n",__LINE__);
//将套接字设置为监听状态
if(listen(sfd, 128) < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("listen");
return -1;
}
printf("listen success __%d__\n",__LINE__);
//存储客户信息
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
pid_t pid = 0;
while(1)
{
int newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("accept");
return -1;
}
printf("客户端连接成功\n");
pid = fork();
if(0 == pid)
{
close(sfd);
do_cli_msg(newfd,cin);
close(newfd);
exit(0);
}
if(pid > 0)
{
close(newfd);
}
else
{
fprintf(stderr,"line:%d ",__LINE__);
perror("fork");
return -1;
}
}
//关闭文件描述符
close(sfd);
return 0;
}
/*
* function: 子进程中用于处理客户端交互的功能
* @param [ in]
* @param [out]
* @return
*/
int do_cli_msg(int newfd,struct sockaddr_in cin)
{
char buf[128];
ssize_t res;
ssize_t rec;
while(1)
{
/*newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("accept");
return -1;
}
printf("accept success,newfd=%d __%d__\n",newfd,__LINE__);
bzero(buf,sizeof(buf));*/
//接受
res = recv(newfd,buf,sizeof(buf),0);
if(res < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("recv");
return -1;
}
else if(0 == res)
{
printf("客户端下线\n");
break;
}
printf("newfd=%d : %s __%d__\n",newfd,buf,__LINE__);
//发送
rec = send(newfd,buf,sizeof(buf),0);
if(rec < 0)
{
fprintf(stderr,"line:%d ",__LINE__);
perror("send");
return -1;
}
else if(rec > 0)
{
printf("send success\n");
}
printf("newfd=%d : %s __%d__\n",newfd,buf,__LINE__);
}
return 0;
}
多进程并发服务器TCP
最新推荐文章于 2024-08-14 15:25:13 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)