多进程实现网络通信(TCP)
服务器端函数
#include <myhead.h>
#define PORT 8848
#define IP "192.168.60.78"
#define BACKLOG 20
void fun(int sss)
{if(sss==SIGCHLD){waitpid(-1,NULL,0);}
}
int main(int argc, const char *argv[])
{if(signal(SIGCHLD,fun)==SIG_ERR){perror("signal");return -1;}//int oldfd=socket(AF_INET,SOCK_STREAM,0);if(oldfd==-1){perror("socket");return -1;}//struct sockaddr_in server={.sin_family=AF_INET,.sin_port=htons(PORT),.sin_addr.s_addr=inet_addr(IP),};if((bind(oldfd,(struct sockaddr *)&server,sizeof(server))==-1)){perror("bind"); return -1;}//int n=11;if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n))==-1){perror("setsockopt");return -1; }printf("端口复用成功|\n");//if(listen(oldfd,BACKLOG)==-1){perror("listen");return -1;}//struct sockaddr_in client;socklen_t client_len=sizeof(client);char buff[1024];
while(1)
{pid_t pid=fork();int newfd=accept(oldfd,(struct sockaddr*)&client,&client_len);if(newfd==-1){perror("accept");return -1;}if(pid==0){printf("来自%s的连接",inet_ntoa(client.sin_addr));close(oldfd);while(1){memset(buff,0,sizeof(buff));int len=recv(newfd,buff,sizeof(buff),0);if(len==0){printf("客户端下线\n");break;}printf("消息:%s\n",buff);strcat(buff,"ok"); send(newfd,buff,sizeof(buff),0);}close(newfd);exit(0);}else if(pid>0){close(newfd);}else{perror("fork");return -1;}}return 0;
}
客户端函数
#include <myhead.h>
#define PORT 8848
#define IP "192.168.60.78"
int main(int argc, const char *argv[])
{int oldfd=socket(AF_INET,SOCK_STREAM,0);if(oldfd==-1){perror("socket");return -1;}//struct sockaddr_in server={.sin_family=AF_INET,.sin_port=htons(PORT),.sin_addr.s_addr=inet_addr(IP),};if((connect(oldfd,(struct sockaddr *)&server,sizeof(server)))==-1){perror("connect"); return -1;}char buff[1024];while(1){fgets(buff,sizeof(buff),stdin);buff[strlen(buff)-1]='\0';send(oldfd,buff,sizeof(buff),0);int len=recv(oldfd,buff,sizeof(buff),0);if(len==0){printf("服务器下线\n");break;}printf("服务器消息:%s\n",buff);}return 0;
}