Question: How to design the server corresponding to the client?

TCP communication framework design

image.png

Server

  • Responsible for monitoring connection status

    • Connect : Generate a communication client (TcpClient), and give event notifications
    • Close : give event notification and destroy client
  • Responsible for monitoring data communication status and giving event notifications

Server-side event design

  • EVT_CONN: Triggered when the client connects to the server and creates a TcpClient for communication
  • EVT_DATA: Triggered when client data reaches the server, use TcpClient to read data
  • EVT_CLOSE: Triggered when the client disconnects from the service, the related TcpClient will be destroyed

image.png

Question: How does the server know when to notify the event callback?

服务端通过 select 机制触发事件回调!

image.png

Server interface design

 typedef void TcpServer;
typedef void (*Listener)(TcpClient*, int);

enum {
    EVT_CONN,
    EVT_DATA,
    EVT_CLOSE
};

TcpServer *TcpServer_New();
int TcpServer_Start(TcpServer *server, int port, int max);
void TcpServer_Stop(TcpServer *server);
void TcpServer_SetListener(TcpServer *server, Listener listener);
int TcpServer_IsValid(TcpServer *server);
void TcpServer_DoWork(TcpServer *server);
void TcpServer_Del(TcpServer *server);

Server-side key code implementation - initialization

 typedef struct tcp_server {
    int fd;
    int valid;
    Listener cb;
    TcpClient *client[FD_SIZE];
}Server;

TcpServer *TcpServer_New()
{
    Server *ret = malloc(sizeof(Server));

    if (ret) {
        int i = 0;

        ret->fd = -1;
        ret->valid = 0;
        ret->cb = NULL;
    }

    return ret;
}

Server-side key code implementation - event monitoring

 FD_ZERO(&reads);
FD_SET(s->fd, &reads);

max = s->fd;

while (s->valid) {
    rset = reads;
    
    timeout.tv_sec = 0;
    timeout.tv_usec = 5000;

    num = select(max+1, &rset, 0, 0, &timeout);

    if (num > 0) {
        max = SelectHandler(s, &rset, &reads, num, mac);
    }
}

Server key code implementation - connection events & data events

 if (index == s->fd) {  // 连接事件
    struct sockaddr_in caddr = {0};
    socklen_t asize = sizeof(caddr);
    
    index = accept(s->fd, (struct sockaddr*)&addr, &asize);

    if (index > -1) {
        FD_SET(index, reads);

        ret = (index > max) ? index : max;
        
        s->client[index] = TcpClient_From(index);

        event = EVT_CONN;
    }
} else {    // 数据事件
    event = EVT_DATA;
}

Server key code implementation - disconnect event & event notification

 if (s->cb) {
    if (TcpClient_IsValid(s->client[index])) {
        s->cb(s->client[index], event);  // EVT_CONN & EVT_DATA 事件通知
    } else {
        if (s->client[index]) {
            s->cb(s->client[index], EVT_CLOSE);  // 断连事件通知
            
            TcpClient_Del(s->client[index]);

            s->client[index] = NULL;
            
            FD_CLR(index, reads);
        }
    }
}

programming experiment

tcp_server.h
 #ifndef TCP_SERVER_H
#define TCP_SERVER_H

#include "tcp_client.h"

typedef void TcpServer;
typedef void (*Listener)(TcpClient*, int);

enum {
    EVT_CONN,
    EVT_DATA,
    EVT_CLOSE
};

TcpServer *TcpServer_New();
int TcpServer_Start(TcpServer *server, int port, int max);
void TcpServer_Stop(TcpServer *server);
void TcpServer_SetListener(TcpServer *server, Listener listener);
int TcpServer_IsValid(TcpServer *server);
void TcpServer_DoWork(TcpServer *server);
void TcpServer_Del(TcpServer *server);

#endif
tcp_server.c
 #include "tcp_server.h"
#include "tcp_client.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/tcp.h> 
#include <arpa/inet.h>
#include <unistd.h>
#include <malloc.h>

#define FD_SIZE 1024

typedef struct tcp_server {
    int fd;
    int valid;
    Listener cb;
    TcpClient *client[FD_SIZE];
}Server;

TcpServer *TcpServer_New()
{
    Server *ret = malloc(sizeof(Server));

    if (ret) {
        int i = 0;

        ret->fd = -1;
        ret->valid = 0;
        ret->cb = NULL;

        for (i=0; i<FD_SIZE; ++i) {
            ret->client[i] = NULL;
        }
    }   

    return ret;
}

int TcpServer_Start(TcpServer *server, int port, int max)
{
    Server *s = (Server*)server;

    if (s && !s->valid) {
        struct sockaddr_in saddr = {0};

        s->fd = socket(PF_INET, SOCK_STREAM, 0);

        s->valid = (s->fd != -1);

        saddr.sin_family = AF_INET;
        saddr.sin_addr.s_addr = htonl(INADDR_ANY);
        saddr.sin_port = htons(port);

        s->valid = s->valid && (bind(s->fd, (struct sockaddr*)&saddr, sizeof(saddr)) != -1);
        s->valid = s->valid && (listen(s->fd, max) != -1);
    }

    return s->valid;
}

void TcpServer_Stop(TcpServer *server)
{
    Server *s = (Server*)server;

    if (s) {
        int i =0;

        s->valid = 0;

        close(s->fd);

        for (i=0; i<FD_SIZE; ++i) {
            TcpClient_Del(s->client[i]);
            s->client[i] = NULL;
        }
    }
}

void TcpServer_SetListener(TcpServer *server, Listener listener)
{
    Server *s = (Server*)server;

    if (s) {
        s->cb = listener;
    }
}

int TcpServer_IsValid(TcpServer *server)
{
    return server ? ((Server*)server)->valid : 0;
}

static int SelectHandler(Server *s, fd_set *rset, fd_set *reads, int num, int max)
{
    int ret = max;
    int i =0;

    for (i=0; i<=max; ++i) {
        if (FD_ISSET(i, rset)) {
            int index = i;
            int event = -1;

            if (index == s->fd) {
                struct sockaddr_in caddr = {0};
                socklen_t asize = sizeof(struct sockaddr_in);

                index = accept(s->fd, (struct sockaddr*)&caddr, &asize);

                if (index > -1) {
                    FD_SET(index, reads);

                    ret = (index > max) ? index : max;

                    s->client[index] = TcpClient_From(index);

                    event = EVT_CONN;
                }
            }
            else {
                event = EVT_DATA;
            }
         
            if (s->cb) {
                if (TcpClient_IsValid(s->client[index])) {
                    s->cb(s->client[index], event);
                } else {
                    if (s->client[index]) {
                        s->cb(s->client[index], EVT_CLOSE);
                    }

                    TcpClient_Del(s->client[index]);

                    s->client[index] = NULL;

                    FD_CLR(index, reads);
                }
            }
        }
    }

    return ret;
}

void TcpServer_DoWork(TcpServer *server)
{
    Server *s = (Server*)server;

    if (s && s->valid) {
        int max = 0;
        int num = 0;
        fd_set reads = {0};
        fd_set rset = {0};
        struct timeval timeout = {0};

        FD_ZERO(&reads);
        FD_SET(s->fd, &reads);

        max = s->fd;

        while (s->valid) {
            rset = reads;

            timeout.tv_sec = 0;
            timeout.tv_usec = 10000;

            num = select(max + 1, &rset, 0, 0, &timeout);

            if (num > 0) {
                max = SelectHandler(s, &rset, &reads, num, max);
            }
        }
    }
}

void TcpServer_Del(TcpServer *server)
{
    TcpServer_Stop(server);
    free(server);
}
Test: server.c
 #include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "tcp_server.h"

void EventListener(TcpClient *client, int evt) 
{
    if (evt == EVT_CONN) {
        printf("Connect: %p\n", client);
    } else if (evt == EVT_DATA) {
        Message *m = TcpClient_RecvMsg(client);

        if (m) {
            char *s = TcpClient_GetDate(client);

            if (m->index == 0) {
                s = malloc(m->total + 1);

                TcpClient_SetData(client, s);
            }

            strcpy(s+m->index, m->payload);

            if ((m->index + 1) == m->total) {
                printf("Data: %s\n", s);
                free(s);
            }

            free(m);
        }
    }
    else if (evt == EVT_CLOSE) {
        printf("close: %p\n", client);
    }
}

int main()
{   
    TcpServer *server = TcpServer_New();

    if (server) {
        int r = TcpServer_Start(server, 8888, 20);

        if (r) {
            TcpServer_SetListener(server, EventListener);
            TcpServer_DoWork(server);
        }
    }

    return 0;
}
output:
 Connect: 0x5602eb035690
Data: D.T.Software
close: 0x5602eb035690

TianSong
737 声望139 粉丝

阿里山神木的种子在3000年前已经埋下,今天不过是看到当年注定的结果,为了未来的自己,今天就埋下一颗好种子吧