cs
ubuntu@ubuntu:wangluobianchen$ cat 循环服务器模型.c
#include <myhead.h>
#define IP "192.168.124.39"
#define PORT 8888
void handle(int sss)
{
if(sss=SIGCHLD)
{
while(waitpid(-1,NULL,WNOHANG)>0);//非阻塞循环回收子进程资源
}
printf("回收成功\n");
}
int main(int argc, const char *argv[])
{
//1.创建套接字
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("oldfd");
return -1;
}
int k=999;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&k,sizeof(k))==-1)
{
perror("setsockopt");
return -1;
}
printf("端口号快速复用成功\n");
//2.绑定
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;
}
//3.监听
if(listen(oldfd,20)==-1)
{
perror("listen");
return -1;
}
//4.父进程连接新的客户端
struct sockaddr_in client;
int client_len=sizeof(client);
while(1)
{
int newfd=accept(oldfd,(struct sockaddr *)&client,&client_len);
if(newfd==-1)
{
perror("accept");
return -1;
}
printf("%s:%d\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));//输出新客户端
//创建子父进程
pid_t pid =fork();
char buff[1024];
if(pid>0)
{
if(signal(SIGCHLD,handle)==SIG_ERR)//绑定子进程退出时的信号
{
perror("signal");
return -1;
}
//父进程关闭新的描述符
close(newfd);
}
else if(pid==0)
{
//子进程关闭旧的描述符消息收发
close(oldfd);
while(1)
{
int res=recv(newfd,buff,sizeof(buff),0);
if(res==0)
{
printf("客户端已经退出\n");
break;
}
printf("%s\n",buff);
strcat(buff,"今天周日");
send(newfd,buff,sizeof(newfd),0);
}
exit(EXIT_SUCCESS);//子进程退出
}
else
{
perror("fork");
return -1;
}
}
close(oldfd);
return 0;
}
线程
cs
#include <myhead.h>
#define IP "19.168.124.39"
#define PORT 6666
void *fun(void *fd)
{
int newfd=*(int *)fd;
char buff[1024];
while(1)
{
int res=recv(newfd,buff,sizeof(buff),0);
if(res==0)
{
printf("客户端下载\n");
break;
}
printf("%s\n",buff);
strcat(buff,"5dianfangxue");
send(newfd,buff,sizeof(buff),0);
}
pthread_exit(NULL);//子线程退出
}
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(bind(oldfd,(struct sockaddr *)&server,sizeof(server))==-1)
{
perror("bind");
return -1;
}
//监听
if(listen(oldfd,20)==-1)
{
perror("litsen");
return -1;
}
struct sockaddr_in client;
int client_len =sizeof(client);
int newfd;
pthread_t tid;
while(1)
{
//接收新客户的连入请求
newfd=accept(oldfd,(struct sockaddr *)&client,&client_len);
if(newfd==-1)
{
perror("accept");
return -1;
}
//创建子线程与客户端通话
if(pthread_create(&tid,NULL,fun,&newfd)==-1)
{
perror("pthread_create");
return -1;
}
}
pthread_join(tid,NULL);//回收子线程资源
close(newfd);
close(oldfd);
return 0;
}