笔记脑图
作业:多进程多线程并发服务器实现一遍提交。
多进程
cpp
复制代码
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
#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);
if(oldfd==-1)
{
perror("socket");
return -1;
}
//
int n=1;
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;
}
struct sockaddr_in client;
socklen_t client_len=sizeof(client);
char buff[1024];
while(1)
{
//
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("%s客户端退出\n",inet_ntoa(client.sin_addr));
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;
}
多线程
cpp
复制代码
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
#define BACKLOG 1024
typedef struct
{
struct sockaddr_in client;
int newfd;
}stu;
void *fun(void *sss)
{
int newfd=((stu *)sss)->newfd;
struct sockaddr_in client=((stu *)sss)->client;
printf("%s发来消息\n",inet_ntoa(client.sin_addr));
char buff[1024];
while(1)
{
int len=recv(newfd,buff,sizeof(buff),0);
if(len==0)
{
printf("客户端退出\n");
break;
}
printf("收到消息:%s\n",buff);
strcat(buff,"1973");
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,BACKLOG)==-1)
{
perror("listen");
return -1;
}
struct sockaddr_in client;
socklen_t client_len=sizeof(client);
while(1)
{
int newfd=accept(oldfd,(struct sockaddr *)&client,&client_len);
stu a;
a.newfd=newfd;
a.client=client;
pthread_t tid;
tid=pthread_create(&tid,NULL,fun,&a);
if(tid==-1)
{
perror("pthread_create");
return -1;
}
pthread_detach(tid);
}
return 0;
}