并发服务器模型
1.多进程模型
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/wait.h>
typedef void (*sighandler_t)(int);
#define ERR_MSG(msg) {printf("line=%d\n",__LINE__);perror(msg);}
#define IP "192.168.21.141"
#define PORT 8888
void handler(int p)
{
while(waitpid(-1,NULL,WNOHANG)>0);
return ;
}
int main(int argc, const char *argv[])
{
sighandler_t s=signal(17,handler);
int reuse=1;
int sfd=socket(AF_INET,SOCK_STREAM,0);
if (sfd<0)
{
ERR_MSG("socket");
return -1;
}
setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
if (bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
if (listen(sfd,12)<0)
{
ERR_MSG("listen");
return -1;
}
pid_t pid;
int cfd;
char buf[128]="";
ssize_t res;
while(1)
{
struct sockaddr_in connect_done;
socklen_t len=sizeof(connect_done);
cfd=accept(sfd,(struct sockaddr*)&connect_done,&len);
if (cfd<0)
{
ERR_MSG("accept");
return -1;
}
pid=fork();
if (pid==0)
{
close(sfd);
while(1)
{
bzero(buf,sizeof(buf));
res=recv(cfd,buf,sizeof(buf),0);
printf("客户端消息:%s\n",buf);
if (res<0)
{
ERR_MSG("recv");
return -1;
}
else if(res==0)
{
printf("客户端关闭\n");
return -1;
}
strcat(buf,"--");
send(cfd,buf,sizeof(buf),0);
}
close(cfd);
}
else if(pid>0)
{
close(cfd);
}
else if(pid<0)
{
ERR_MSG("fork");
return -1;
}
}
return 0;
}
2.多线程模型
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#define ERR_MSG(msg) {printf("line=%d\n",__LINE__);perror(msg);}
#define IP "192.168.21.141"
#define PORT 8888
void *callback(void *p)
{
char buf[128]="";
ssize_t res;
int cfd=*(int* )p;
while(1)
{
bzero(buf,sizeof(buf));
res=recv(cfd,buf,sizeof(buf),0);
printf("客户端消息:%s\n",buf);
if (res<0)
{
ERR_MSG("recv");
return NULL;
}
else if(res==0)
{
printf("客户端关闭\n");
return NULL;
}
strcat(buf,"--");
send(cfd,buf,sizeof(buf),0);
}
close(cfd);
exit(0);
}
int main(int argc, const char *argv[])
{
int reuse=1;
int sfd=socket(AF_INET,SOCK_STREAM,0);
if (sfd<0)
{
ERR_MSG("socket");
return -1;
}
setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
if (bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
if (listen(sfd,12)<0)
{
ERR_MSG("listen");
return -1;
}
pthread_t pt;
int cfd;
while(1)
{
struct sockaddr_in connect_done;
socklen_t len=sizeof(connect_done);
cfd=accept(sfd,(struct sockaddr*)&connect_done,&len);
if (cfd<0)
{
ERR_MSG("accept");
return -1;
}
if (pthread_create(&pt,NULL,callback,&cfd)<0)
{
ERR_MSG("pthread_create");
return -1;
}
}
close(sfd);
return 0;
}