网络编程实战框架 四、tcp_server_init()
发布日期:2021-05-06 23:39:07 浏览次数:36 分类:精选文章

本文共 3164 字,大约阅读时间需要 10 分钟。

一个基于事件驱动的TCP服务器实现

结构体定义

TCP服务器

TCP服务器是一个用于处理TCP连接的核心组件,主要负责监听、接受新连接并管理已有连接。其主要结构如下:

struct TCPserver {
int port; // 服务端口号
struct event_loop *eventLoop; // 事件循环
struct acceptor *acceptor; // 接收连接的acceptor
connection_completed_call_back connectionCompletedCallBack; // 连接建立完成的回调
message_call_back messageCallBack; // 数据接收完成的回调
write_completed_call_back writeCompletedCallBack; // 数据写入完成的回调
connection_closed_call_back connectionClosedCallBack; // 连接关闭的回调
int threadNum; // 线程池中的线程数量
struct thread_pool *threadPool; // 线程池
void *data; // 回调数据
};
线程池

线程池用于管理和分配处理连接的线程。每个线程运行一个事件循环,负责处理特定的I/O任务。线程池的结构如下:

struct thread_pool {
struct event_loop *mainLoop; // 主线程的事件循环
int started; // 是否已经启动
int thread_number; // 线程总数
struct event_loop_thread *eventLoopThreads; // 维护线程的数组
int position; // 当前选择服务的线程位置
};

初始化逻辑

tcp_server_init函数

这个函数负责初始化TCP服务器的核心配置,包括线程池的创建和各个回调函数的注册。

struct TCPserver *tcp_server_init(struct event_loop *eventLoop, 
struct acceptor *acceptor,
connection_completed_call_back connectionCompletedCallBack,
message_call_back messageCallBack,
write_completed_call_back writeCompletedCallBack,
connection_closed_call_back connectionClosedCallBack,
int threadNum) {
struct TCPserver *tcpServer = malloc(sizeof(struct TCPserver));
tcpServer->eventLoop = eventLoop;
tcpServer->acceptor = acceptor;
tcpServer->connectionCompletedCallBack = connectionCompletedCallBack;
tcpServer->messageCallBack = messageCallBack;
tcpServer->writeCompletedCallBack = writeCompletedCallBack;
tcpServer->connectionClosedCallBack = connectionClosedCallBack;
tcpServer->threadNum = threadNum;
tcpServer->threadPool = thread_pool_new(eventLoop, threadNum);
tcpServer->data = NULL;
return tcpServer;
}
thread_pool_new函数

这个函数负责创建并初始化线程池,负责管理和分配线程。

struct thread_pool *thread_pool_new(struct event_loop *mainLoop, int threadNumber) {
struct thread_pool *threadPool = malloc(sizeof(struct thread_pool));
threadPool->mainLoop = mainLoop;
threadPool->position = 0;
threadPool->thread_number = threadNumber;
threadPool->started = 0;
threadPool->eventLoopThreads = NULL;
return threadPool;
}

主函数调用

在实际应用中,通常会按照以下步骤初始化TCP服务器:

struct TCPserver *tcpServer = tcp_server_init(eventLoop, acceptor, 
onConnectionCompleted,
onMessage,
onWriteCompleted,
onConnectionClosed,
4);

工作流程

  • 初始化TCP服务器:通过tcp_server_init函数初始化TCP服务器配置,包括事件循环、acceptor、回调函数以及线程池配置。
  • 创建线程池:线程池负责管理多个线程,用于处理TCP连接的I/O操作。
  • 启动服务器:将TCP服务器注册到事件循环,开始监听并接受新连接。
  • 处理连接:当新连接建立时,调用connectionCompletedCallBack回调函数;当数据接收完成时,调用messageCallBack;当数据写入完成时,调用writeCompletedCallBack;当连接关闭时,调用connectionClosedCallBack
  • 结论

    通过上述结构和流程,可以实现一个高效的基于事件驱动的TCP服务器。线程池的引入使服务器能够在多线程环境下处理大量连接,同时保持良好的性能和扩展性。

    上一篇:ntp同步的问题
    下一篇:麻烦来了,服务器什么情况

    发表评论

    最新留言

    做的很好,不错不错
    [***.243.131.199]2025年03月21日 06时00分15秒