ChatServer/testmuduo/muduo_server.cpp

73 lines
1.8 KiB
C++
Raw Normal View History

2024-12-23 20:55:55 +08:00
/*
muduo网络库给用户提供了两个主要的类
TcpServer
TcpClient
epoll+线
I/O的代码和业务代码区分开
*/
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <iostream>
2024-12-25 20:01:55 +08:00
#include <functional>
2024-12-23 20:55:55 +08:00
using namespace std;
using namespace muduo;
using namespace muduo::net;
2024-12-25 20:01:55 +08:00
using namespace placeholders;
2024-12-23 20:55:55 +08:00
2024-12-26 16:50:27 +08:00
/*
muduo网络库开发服务器程序
1.TcpServer对象
2.
3.TcpServer构造函数需要什么参数ChatServer的构造函数
4.
5.线,muduo库会自己分配I/O线程和worker线程
*/
2024-12-23 20:55:55 +08:00
class ChatServer{
public:
ChatServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg)
:_server(loop,listenAddr,nameArg),_loop(loop)
{
2024-12-25 20:01:55 +08:00
//给服务器注册用户连接的创建和断开回调
_server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));
2024-12-26 16:50:27 +08:00
2024-12-25 20:01:55 +08:00
//给服务器注册用户读写事件的回调
2024-12-26 16:50:27 +08:00
_server.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));
//设置服务器端的线程数量 1个I/O线程 3个worker线程
_server.setThreadNum(4);
2024-12-23 20:55:55 +08:00
}
2024-12-26 16:50:27 +08:00
void start(){
_server.start();
}
2024-12-23 20:55:55 +08:00
private:
2024-12-25 20:01:55 +08:00
void onConnection(const TcpConnectionPtr&)
{
}
2024-12-26 16:50:27 +08:00
void onMessage(const TcpConnectionPtr& conn,
Buffer* buffer,
Timestamp time)
2024-12-25 20:01:55 +08:00
{
}
2024-12-23 20:55:55 +08:00
TcpServer _server;
EventLoop* _loop;
};