C++项目 | 集群聊天服务器 | 网络模块

写一个模块测试一个模块

头文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//chatserver.hpp
#ifndef CHATSERVER_H
#define CHATSERVER_H

#include<muduo/net/TcpServer.h>
#include<muduo/net/EventLoop.h>
#include<functional>

using namespace muduo;
using namespace muduo::net;

//聊天服务器的主类
class ChatServer
{
public:
//初始化聊天服务器对象
ChatServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg);
//启动服务
void start();
//


private:
//上报连接创建关闭相关信息的回调函数
void onConnection(const TcpConnectionPtr&);

//上报读写时间相关信息的回调函数
void onMessage(const TcpConnectionPtr&,Buffer*,Timestamp);
TcpServer _server;//组合的muduo库,实现服务器功能的类对象
EventLoop* _loop;//指向事件循环对象的指针
};

#endif

根据muduo网络库实现的,主要处理连接事件和读写事件

具体实现的cpp文件

具体实现ChatServer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//chatserver.cpp
#include"chatserver.hpp"

using namespace std;
using namespace placeholders;

//初始化聊天服务器对象
ChatServer::ChatServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg)
:_server(loop,listenAddr,nameArg),
_loop(loop)
{
//注册连接回调
_server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));

//注册消息回调
_server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));

//设置线程数量
_server.setThreadNum(4);
}

//启动服务
void ChatServer::start()
{
_server.start();
}

//上报连接创建关闭相关信息的回调函数
void ChatServer::onConnection(const TcpConnectionPtr&)
{

}

//上报读写时间相关信息的回调函数
void ChatServer::onMessage(const TcpConnectionPtr&,Buffer*,Timestamp)
{

}

测试文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//main.cpp
#include"chatserver.hpp"
#include<iostream>
using namespace std;

int main()
{
EventLoop loop;
InetAddress addr("127.0.0.1",6000);
ChatServer server(&loop,addr,"ChatServer");

server.start();
loop.loop();
return 0;
}
1
2
3
cd build
cmake ..
make

image-20250118143209968