并发服务器设计

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

并发服务器就是能够同时处理多个客户端请求的服务器。并发服务器可通过多进程或者多线程程序来实现,这里采用多进程程序。

服务器

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>/*定义了struct sockaddr_in*/
void main()
{
    int sockfd;
    /*创建socket*/
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1)
    {
        printf("create socket false");
        exit(1);    
    }
    /*绑定地址*/
    struct sockaddr_in server_addr;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(5000);
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    if(bind(sockfd,(const struct sockaddr *)(&server_addr),sizeof(server_addr))==-1)
    {
        printf("bind false");
        exit(1);    
    }
    /*监听端口*/
    listen(sockfd,3);
    /*父进程等待连接,成功连接后创建子进程收发数据*/
    int newfd;
    struct sockaddr_in client_addr;
    int addrlen=sizeof(client_addr);
    char buf[128];
    pid_t pid;
    while(1)
    {
        newfd=accept(sockfd,(struct sockaddr *)(&client_addr),&addrlen);
        pid=fork();
        if(pid==0)
        {
            while(1)
            {
                recv(newfd,buf,128,0);
                printf("the message is from :%s\n",inet_ntoa(client_addr.sin_addr));
                printf("the message received is %s\n",buf);
                if(strcmp(buf,"exit")==0)
                {
                    break;  
                }

            }
            close(newfd);
            close(sockfd);
            exit(0);
        }
    }
    /*结束连接*/
    close(newfd);
    close(sockfd);
}

客户端

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>/*定义了struct sockaddr_in*/
void main()
{
    /*创建socket*/
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1)
    {
        printf("create socket false");
        exit(1);    
    }
    /*连接服务器*/
    struct sockaddr_in server_addr;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(5000);
    server_addr.sin_addr.s_addr=inet_addr("192.168.137.246");
    if(connect(sockfd,(const struct sockaddr *)(&server_addr),sizeof(server_addr))==-1)
    {
        printf("connect false");
        exit(1);    
    }
    /*收发数据*/
    printf("please enter your message,and exit for exit\n");
    char buf[128];
    while(1)
    {
        scanf("%s",buf);
        send(sockfd,buf,128,0);
        if(strcmp(buf,"exit")==0)
            break;
    }
    /*结束连接*/
    close(sockfd);
}

来自:http://blog.csdn.net/u011012049/article/details/47452669