服务器代码:
#include <myhead.h>
#define IP "192.168.128.59"
#define PORT 8888
#define BACKLOG 20
void fun(int sss)
{if(sss=SIGCHLD){while(waitpid(-1,NULL,0)>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);//创建TCP类型的套接字if(oldfd==-1){perror("socket");return -1;}int n;int len=sizeof(n);if(getsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&n,&len)==-1)//端口号快速复用检测{perror("getsockopt");return -1;}if(n){printf("端口号快速复用已启用\n");}else{printf("端口号快速复用未启用\n");}n=999;if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n))==-1)//端口号快速复用成功{perror("setsockopt");return -1;}printf("端口号快速复用成功\n");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;}if(listen(oldfd,BACKLOG)==-1)//监听{perror("listen");return -1;}char buff[1024];struct sockaddr_in client;socklen_t client_len=sizeof(client);while(1){int newfd=accept(oldfd,(struct sockaddr*)&client,&client_len);if(newfd==-1){perror("accept");return -1;}printf("%s发来了连接请求\n",inet_ntoa(client.sin_addr));pid_t pid=fork();if(pid>0){close(newfd);}else if(pid==0){close(oldfd);while(1){int len=recv(newfd,buff,sizeof(buff),0);if(len==0){printf("客户端退出\n");break;}printf("客户端%s发来消息:%s\n",inet_ntoa(client.sin_addr),buff);strcat(buff,inet_ntoa(client.sin_addr));send(newfd,buff,sizeof(buff),0);}close(newfd);exit(0);}else{perror("fork");return -1;}}return 0;
}
客户端代码:
#include <myhead.h>
#define IP "192.168.128.59"
#define PORT 8888
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;
}