Liunx网络编程---并发服务器
网络程序里面,一般来说都是许多用户共同访问一个服务器,为了处理客户的需求,对服务器提出了特殊的要求,目前有两种;
循环服务器:
服务器在同一时刻只能处理一个客户请求
并发服务器;
服务器能在同一时刻能够处理多个用户的请求
网络服务器大多采用并发,并发服务器的原理就是专门制造一个子进程,由子进程负责处理客户端的请求,父进程继续等待新的客户请求。下面是将TCP循环服务器改进的并发服务器:
//TCP text,this is a TCP server
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define portnumber 4443
int main()
{
struct sockaddr_in TCP_server,TCP_client;
int socketfd,newfd;
int tbyte;
if((socketfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
fprintf(stderr,"Get socket error! %s \n",strerror(errno));
exit(1);
}
printf("set up the socket,and sockfd is %d\n",socketfd);
/*write the server address*/
bzero(&TCP_server,sizeof(struct sockaddr_in));
TCP_server.sin_family = AF_INET;
TCP_server.sin_port = htons(portnumber);
TCP_server.sin_addr.s_addr = htonl(INADDR_ANY);
/*bind ip to socket*/
if(bind(socketfd,(struct sockaddr *)(&TCP_server),sizeof(struct sockaddr)) == -1)
{
perror("Bind error:\n");
exit(1);
}
if(listen(socketfd,5) == -1)
{
printf("set the max connect error!\n");
exit(1);
}
while(1)
{
bzero(&TCP_client,sizeof(struct sockaddr_in));
tbyte = sizeof(struct sockaddr_in);
if((newfd = accept(socketfd,(struct sockaddr*)(&TCP_client),&tbyte)) == -1)
{
fprintf(stderr,"TCP connect failed: %s\n",strerror(errno));
exit(1);
}
/*create a child progress to solve the telecommuncation*/
if(fork() == 0) //child progross
{
char buffer[1024];
printf("Get message from: %s\n",inet_ntoa(TCP_client.sin_addr));
if((tbyte = read(newfd,buffer,1024)) == -1)
{
printf("Get message error!\n");
exit(1);
}
buffer[tbyte] = '\0';
printf("%s\n",buffer);
memset(buffer,'\0',1024);
close(newfd);
close(socketfd);
exit(0);
}else //parents progress
{
close(newfd);
}
}
return 0;
}
如上,改进后的TCP_server就可以同时处理多个客户的请求。