【C++从零实现Json-Rpc框架】第四弹——使用Muduo库实现英译汉

目录
●void setConnectionCallback(ConnectionCallback cb)
●void setMessageCallback(MessageCallback cb)
一、前言
在本文将会为大家介绍Muduo库常用的一些接口,并借助这些接口来实现一个简单版的英译汉服务器和客户端,希望能够帮助大家加深对Muduo库的使用!!!!
二、正文
1.Muduo库常见接口介绍
1.1 TcpServer类基础介绍
● TcpConnectionPtr
typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;TcpConnectionPtr属于TcpConnection类,但是我们在编写服务器的时候也需要接受客户端的连接,当连接到来的时候,由连接事件的回调函数来处理连接
● ConnectionCallback
typedef std::function<void (const TcpConnectionPtr&)> ConnectionCallback;ConnectionCallback是服务器处理连接事情的回调函数,当有来自客户端的连接到来时,就会自动调用该函数来处理连接
● MessageCallback
typedef std::function<void (const TcpConnectionPtr&, Buffer*, Timestamp)> MessageCallback;MessageCallback是服务器处理连接消息的回调函数,当客户端传来消息时,就会自动调用该函数来处理消息
● InetAddress
class InetAddress : public muduo::copyable { public: InetAddress(StringArg ip, uint16_t port, bool ipv6 = false); };InetAddress 字段与服务器的设置有关,该字段将ip,port与ipv6合并成为一个字段,当我们设置服务器的时候就需要传递该字段,来指明服务器的ip地址,端口号和是否采取ipv6。
● TcpServer
class TcpServer : noncopyable { public: enum Option { kNoReusePort, kReusePort, }; TcpServer(EventLoop* loop,const InetAddress& listenAddr,const string& nameArg,Option option = kNoReusePort); void setThreadNum(int numThreads); void start(); /// 当⼀个新连接建⽴成功的时候被调⽤ void setConnectionCallback(const ConnectionCallback& cb { connectionCallback_ = cb; } ///消息的业务处理回调函数--这是收到新连接消息的时候被调⽤的函数 void setMessageCallback (const MessageCallback& cb) { messageCallback_ = cb; } };TcpServer类则是我们等会字典服务器要使用的主体,在其构造函数中我们要传递InetAddress字段,表明ip和端口号;传递EventLoop指针来进行事件监控,Option选项则是指明服务器端口是否服用;start函数则是启动服务器;在启动服务器之前,我们还需要设置连接建立回调函数和消息处理的回调函数
1.2 EventLoop类
class EventLoop : noncopyable { public: /// Loops forever. /// Must be called in the same thread as creation of the object. void loop(); /// Quits loop. /// This is not 100% thread safe, if you call through a raw pointer, /// better to call through shared_ptr<EventLoop> for 100% safety. void quit(); TimerId runAt(Timestamp time, TimerCallback cb); /// Runs callback after @c delay seconds. /// Safe to call from other threads. TimerId runAfter(double delay, TimerCallback cb); /// Runs callback every @c interval seconds. /// Safe to call from other threads. TimerId runEvery(double interval, TimerCallback cb); /// Cancels the timer. /// Safe to call from other threads. void cancel(TimerId timerId); private: std::atomic<bool> quit_; std::unique_ptr<Poller> poller_; mutable MutexLock mutex_; std::vector<Functor> pendingFunctors_ GUARDED_BY(mutex_); };EventLoop类是帮助我们服务器进行事件监控的,一旦调用loop( )函数就会一直死循环进入事件监控的状态
1.3 TcpConnection类
class TcpConnection : noncopyable, public std