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
| #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; 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
| #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
| #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; }
|
