TCP并发服务器模型(二)

本篇博客讲述单客户端单进程的TCP服务器并发模型。该模型由主进程统一处理客户端的连接,当接收到客户端连接后再临时fork()进程,由子进程处理客户请求。

模型如下图所示:

例程:
结合图示,程序易懂,代码就不解释了。
服务器端代码:

/* author:arvik purpose:test the server simultaneity email:[email protected] csdn: http://blog.csdn.net/u012819339 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>


#define BUFFLEN 1024
#define SERVER_PORT 8887
#define BACKLOG 3

static void handle_request(int s_c)
{
    time_t now;
    char buff[BUFFLEN];
    int n = 0;

    memset(buff, 0, sizeof(buff));
    n = recv(s_c, buff, BUFFLEN, 0);

    if(n>0)
    {
        printf("receive msg from client: %s\n", buff);
    }

    close(s_c);
}


static int handle_connect(int s_s)
{
    int s_c;
    struct sockaddr_in from;
    socklen_t len = sizeof(from);
    pid_t pid;

    while(1)
    {
        s_c = accept(s_s, (struct sockaddr*)&from, &len); //block
        if(s_c>0)
        {
            pid = fork();
            if(pid>0) //parent
                close(s_c);
            else
            {
                handle_request(s_c);
                return 0;
            }
        }
    }
}


int main()
{
    int s_s;
    struct sockaddr_in local;

    s_s = socket(AF_INET, SOCK_STREAM, 0);

    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = inet_addr("127.0.0.1");//htonl(INADDR_ANY);
    local.sin_port = htons(SERVER_PORT);

    if(bind(s_s, (struct sockaddr*)&local, sizeof(local)))
    {
        printf("bind socket failed!\n");
        return -1;
    }

    listen(s_s, BACKLOG);

    handle_connect(s_s);

    close(s_s);

    return 0;
}

客户端代码:
和上篇博客中client.c代码一致,代码就不贴了,自己去找好了。地址http://blog.csdn.net/u012819339/article/details/50866116

你可能感兴趣的:(并发,tcp,服务器)