1.c
#include <myhead.h>
#define IP "192.168.60.45"
#define PORT 6666
#define BACKLOG 100
void fun(int sss)
{
if(sss==SIGCHLD)
{
while(waitpid(-1,NULL,0)>0);
}
}
int main(int argc, const char *argv[])
{
//1.捕获子进程退出时的信号
if(signal(SIGCHLD,fun)==SIG_ERR)
{
perror("signal");
return -1;
}
//2.创建TCP类型的套接字
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
//3.端口号快速复用
int n =1;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n))==-1)
{
perror("setsockopt");
return -1;
}
printf("端口号快速复用成功\n");
//4.绑定
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");
}
//5.监听
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
struct sockaddr_in client;
socklen_t client_len = sizeof(client);
while(1)
{
//5.接受客户端连接
int newfd = accept(oldfd,(struct sockaddr *)&client,&client_len);
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);
}
exit(0);
}
else
{
perror("fork");
return -1;
}
}
return 0;
}
2.c
#include <myhead.h>
#define IP "192.168.110.43"
#define PORT 8888
int main(int argc, const char *argv[])
{
//1.创建套接字
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("socket");
return -1;
}
//2.连接服务器
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;
}
//3.数据收发
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);
}
close(oldfd);
return 0;
}