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

打印 上一主题 下一主题

主题 1575|帖子 1575|积分 4725





目录

一、前言
二、正文
1.Muduo库常见接口介绍
1.1 TcpServer类基础介绍
● TcpConnectionPtr
● ConnectionCallback
● MessageCallback
● InetAddress 
● TcpServer
1.2 EventLoop类
1.3 TcpConnection类
1.4 TcpClient类基础介绍
● TcpClient
●void connect()
●void disconnect()
 ●void setConnectionCallback(ConnectionCallback cb)
 ●void setMessageCallback(MessageCallback cb)
1.5 CountDownLatch 类
 1.6 Buffer类基础介绍
 2. Muduo库英译汉服务
2.1 英译汉TCP服务器
2.2 英译汉客户端
2.3 makefile文件
 三、结语


一、前言

           在本文将会为各人介绍Muduo库常用的一些接口,并借助这些接口来实现一个简单版的英译汉服务器和客户端,盼望可以或许资助各人加深对Muduo库的利用!!!!
  二、正文

1.Muduo库常见接口介绍

1.1 TcpServer类基础介绍

● TcpConnectionPtr

  1. typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
复制代码
  TcpConnectionPtr属于TcpConnection类,但是我们在编写服务器的时候也需要接受客户端的毗连,当毗连到来的时候,由毗连事件的回调函数来处理毗连
  ● ConnectionCallback

  1. typedef std::function<void (const TcpConnectionPtr&)> ConnectionCallback;
复制代码
  ConnectionCallback是服务器处理毗连事情的回调函数,当有来自客户端的毗连到来时,就会自动调用该函数来处理毗连
  ● MessageCallback

  1. typedef std::function<void (const TcpConnectionPtr&, Buffer*,
  2. Timestamp)> MessageCallback;
复制代码
   MessageCallback是服务器处理毗连消息的回调函数,当客户端传来消息时,就会自动调用该函数来处理消息
  ● InetAddress 

  1. class InetAddress : public muduo::copyable
  2. {
  3. public:
  4.      InetAddress(StringArg ip, uint16_t port, bool ipv6 = false);
  5. };
复制代码
  InetAddress 字段与服务器的设置有关,该字段将ip,port与ipv6合并成为一个字段,当我们设置服务器的时候就需要传递该字段,来指明服务器的ip地址,端口号和是否采取ipv6。
  ● TcpServer

  1. class TcpServer : noncopyable
  2. {
  3. public:
  4.      enum Option
  5.      {
  6.          kNoReusePort,
  7.          kReusePort,
  8.      };
  9.      
  10.     TcpServer(EventLoop* loop,const InetAddress& listenAddr,const string&         
  11.               nameArg,Option option = kNoReusePort);
  12.     void setThreadNum(int numThreads);
  13.     void start();
  14.      
  15.     /// 当⼀个新连接建⽴成功的时候被调⽤
  16.     void setConnectionCallback(const ConnectionCallback& cb { connectionCallback_ = cb; }
  17.      
  18.     ///消息的业务处理回调函数--这是收到新连接消息的时候被调⽤的函数
  19.     void setMessageCallback (const MessageCallback& cb)
  20.      { messageCallback_ = cb; }
  21. };
复制代码
  TcpServer类则是我们等会字典服务器要利用的主体,在其构造函数中我们要传递InetAddress字段,表明ip和端口号;传递EventLoop指针来进行事件监控,Option选项则是指明服务器端口是否服用;start函数则是启动服务器;在启动服务器之前,我们还需要设置毗连创建回调函数和消息处理的回调函数
  1.2 EventLoop类

  1. class EventLoop : noncopyable
  2. {
  3. public:
  4. /// Loops forever.
  5. /// Must be called in the same thread as creation of the object.
  6. void loop();
  7. /// Quits loop.
  8. /// This is not 100% thread safe, if you call through a raw pointer,
  9. /// better to call through shared_ptr<EventLoop> for 100% safety.
  10. void quit();
  11. TimerId runAt(Timestamp time, TimerCallback cb);
  12. /// Runs callback after @c delay seconds.
  13. /// Safe to call from other threads.
  14. TimerId runAfter(double delay, TimerCallback cb);
  15. /// Runs callback every @c interval seconds.
  16. /// Safe to call from other threads.
  17. TimerId runEvery(double interval, TimerCallback cb);
  18. /// Cancels the timer.
  19. /// Safe to call from other threads.
  20. void cancel(TimerId timerId);
  21. private:
  22. std::atomic<bool> quit_;
  23. std::unique_ptr<Poller> poller_;
  24. mutable MutexLock mutex_;
  25. std::vector<Functor> pendingFunctors_ GUARDED_BY(mutex_);
  26. };
复制代码
  EventLoop类是资助我们服务器进行事件监控的,一旦调用loop( )函数就会不绝死循环进入事件监控的状态 
  1.3 TcpConnection类

  1. class TcpConnection : noncopyable,
  2. public std::enable_shared_from_this<TcpConnection>
  3. {
  4. public:
  5. /// Constructs a TcpConnection with a connected sockfd
  6. ///
  7. /// User should not create this object.
  8. TcpConnection(EventLoop* loop,
  9.                const string& name,
  10.                int sockfd,
  11.                const InetAddress& localAddr,
  12.                const InetAddress& peerAddr);
  13. bool connected() const { return state_ == kConnected; }
  14. bool disconnected() const { return state_ == kDisconnected; }
  15. void send(string&& message); // C++11
  16. void send(const void* message, int len);
  17. void send(const StringPiece& message);
  18. // void send(Buffer&& message); // C++11
  19. void send(Buffer* message);  // this one will swap data
  20. void shutdown(); // NOT thread safe, no simultaneous calling
  21. void setContext(const boost::any& context)
  22. { context_ = context; }
  23. const boost::any& getContext() const
  24. { return context_; }
  25. boost::any* getMutableContext()
  26. { return &context_; }
  27. void setConnectionCallback(const ConnectionCallback& cb)
  28. { connectionCallback_ = cb; }
  29. void setMessageCallback(const MessageCallback& cb)
  30. { messageCallback_ = cb; }
  31. private:
  32. enum StateE { kDisconnected, kConnecting, kConnected, kDisconnecting };
  33. EventLoop* loop_;
  34. ConnectionCallback connectionCallback_;
  35. MessageCallback messageCallback_;
  36. WriteCompleteCallback writeCompleteCallback_;
  37. boost::any context_;
  38. };
复制代码
  在TcpConnection与毗连相干的类常用函数的有:
  ①判定当前的毗连情况——connected() / disconnected()
  ②向毗连的远端服务端发送消息——send()
  1.4 TcpClient类基础介绍

● TcpClient

  1. TcpClient(EventLoop* loop,const InetAddress& serverAddr,
  2. const string& nameArg);
复制代码
  对于TcpClient的构造需要传递loop指针进行事件监控,InetAddress来指明服务端的IP和port,nameArg则是指明TcpClient的定名
  ●void connect()

   调用该函数,TcpClient则会向已经设置好的远端服务器进行毗连 
  ●void disconnect()

   调用该函数,TcpClient则会取消与远端服务器的毗连
   ●void setConnectionCallback(ConnectionCallback cb)

  1. /// 连接服务器成功时的回调函数
  2. void setConnectionCallback(ConnectionCallback cb)
  3. { connectionCallback_ = std::move(cb); }
复制代码
 ●void setMessageCallback(MessageCallback cb)

  1. /// 收到服务器发送的消息时的回调函数
  2. void setMessageCallback(MessageCallback cb)
  3. { messageCallback_ = std::move(cb); }
复制代码
1.5 CountDownLatch 类

   因为 muduo 库不管是服务端还是客⼾端都是异步操作, 对于客⼾端来说如果我们在毗连还没有完全建⽴乐成的时候发送数据,这是不被允许的。 因此我们可以使⽤内置的CountDownLatch 类进⾏同步控制。具体的思路就是给计数器count一个初值,比如说1,当毗连创建乐成的时候,我们将该值镌汰为0,才进行loop的事件监控,否则就不绝处于阻塞等待毗连的状态,避免client还没有创建毗连乐成,就进入事件的监控,这是不符合逻辑的。
  1. class CountDownLatch : noncopyable
  2. {
  3. public:
  4.      explicit CountDownLatch(int count);
  5.      void wait(){
  6.          MutexLockGuard lock(mutex_);
  7.          while (count_ > 0)
  8.          {
  9.              condition_.wait();
  10.          }
  11.      }
  12.      void countDown(){
  13.          MutexLockGuard lock(mutex_);--count_;
  14.          if (count_ == 0)
  15.          {
  16.              condition_.notifyAll();
  17.          }
  18.      }
  19.      int getCount() const;
  20. private:
  21.      mutable MutexLock mutex_;
  22.      Condition condition_ GUARDED_BY(mutex_);
  23.      int count_ GUARDED_BY(mutex_);
  24. };
复制代码
 1.6 Buffer类基础介绍

  1. class Buffer : public muduo::copyable
  2. {
  3. public:
  4. static const size_t kCheapPrepend = 8;
  5. static const size_t kInitialSize = 1024;
  6. explicit Buffer(size_t initialSize = kInitialSize)
  7.      : buffer_(kCheapPrepend + initialSize),
  8.      readerIndex_(kCheapPrepend),
  9.      writerIndex_(kCheapPrepend);
  10. void swap(Buffer& rhs)
  11. size_t readableBytes() const
  12. size_t writableBytes() const
  13. const char* peek() const
  14. const char* findEOL() const
  15. const char* findEOL(const char* start) const
  16. void retrieve(size_t len)
  17. void retrieveInt64()
  18. void retrieveInt32()
  19. void retrieveInt16()
  20. void retrieveInt8()
  21. string retrieveAllAsString()
  22. string retrieveAsString(size_t len)
  23. void append(const StringPiece& str)
  24. void append(const char* /*restrict*/ data, size_t len)
  25. void append(const void* /*restrict*/ data, size_t len)
  26. char* beginWrite()
  27. const char* beginWrite() const
  28. void hasWritten(size_t len)
  29. void appendInt64(int64_t x)
  30. void appendInt32(int32_t x)
  31. void appendInt16(int16_t x)
  32. void appendInt8(int8_t x)
  33. int64_t readInt64()
  34. int32_t readInt32()
  35. int16_t readInt16()
  36. int8_t readInt8()
  37. int64_t peekInt64() const
  38. int32_t peekInt32() const
  39. int16_t peekInt16() const
  40. int8_t peekInt8() const
  41. void prependInt64(int64_t x)
  42. void prependInt32(int32_t x)
  43. void prependInt16(int16_t x)
  44. void prependInt8(int8_t x)
  45. void prepend(const void* /*restrict*/ data, size_t len)
  46. private:
  47. std::vector<char> buffer_;
  48. size_t readerIndex_;
  49. size_t writerIndex_;
  50. static const char kCRLF[];
  51. };
复制代码
    在Buffer类中,我们这次用到的接口是retrieveAllAsString(),由于我们字典翻译的哀求隔断时间比较长,因此默认缓冲区里的数据就是一次完整的翻译哀求,所以我们就利用retrieveAllAsString()接口将缓冲区的数据全部读作为一次完整的哀求
   2. Muduo库英译汉服务

2.1 英译汉TCP服务器

  1. /*
  2.     实现一个翻译服务器,客户端发送过来一个英语单词,返回一个汉语词语
  3. */
  4. #include <muduo/net/TcpServer.h>
  5. #include <muduo/net/EventLoop.h>
  6. #include <muduo/net/TcpConnection.h>
  7. #include <muduo/net/TcpClient.h>
  8. #include <muduo/net/Buffer.h>
  9. #include <iostream>
  10. #include <string>
  11. #include <unordered_map>
  12. class DicServer{
  13. public:
  14.     DicServer(int port)
  15.         :_server(&_baseloop,
  16.         muduo::net::InetAddress("0.0.0.0",port),
  17.         "DicServer",muduo::net::TcpServer::Option::kReusePort)
  18.     {
  19.         //设置连接事件(连接建立/管理)的回调
  20.         _server.setConnectionCallback(std::bind(&DicServer::onConnection,this,std::placeholders::_1));
  21.         //设置连接消息的回调
  22.         _server.setMessageCallback(std::bind(&DicServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
  23.     }
  24.     void start()
  25.     {
  26.         _server.start();    //先开始监听
  27.         _baseloop.loop();   //再开始死循环事件监控
  28.     }
  29. private:
  30.     void onConnection(const muduo::net::TcpConnectionPtr &conn)
  31.     {
  32.         if(conn->connected())
  33.             std::cout<<"连接建立!\n";
  34.         else
  35.             std::cout<<"连接断开!\n";
  36.     }
  37.     void onMessage(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buf,muduo::Timestamp)
  38.     {
  39.         static std::unordered_map<std::string,std::string> dict_map={
  40.             {"hello","你好"},
  41.             {"world","世界"},
  42.             {"worker","打工人"}
  43.         };
  44.         std::string msg=buf->retrieveAllAsString();
  45.         std::string res;
  46.         auto it=dict_map.find(msg);
  47.         if(it != dict_map.end())
  48.             res=it->second;
  49.         else   
  50.             res="未知单词!";
  51.         
  52.         conn->send(res);
  53.     }
  54. public:
  55.     muduo::net::EventLoop _baseloop;
  56.     muduo::net::TcpServer _server;
  57. };
  58. int main()
  59. {
  60.     DicServer server(9090);
  61.     server.start();
  62.     return 0;
  63. }
复制代码
2.2 英译汉客户端

  1. #include <muduo/net/TcpClient.h>
  2. #include <muduo/net/EventLoop.h>
  3. #include <muduo/net/EventLoopThread.h>
  4. #include <muduo/net/TcpClient.h>
  5. #include <muduo/net/Buffer.h>
  6. #include <iostream>
  7. #include <string>
  8. class DictClient{
  9. public:
  10.     DictClient(const std::string &sip,int sport)
  11.         :_baseloop(_loopthrad.startLoop())
  12.         ,_downlatch(1) //初始化计数器为1,只有为0时才会唤醒
  13.         ,_client(_baseloop,muduo::net::InetAddress(sip,sport),"DicClient")
  14.     {
  15.         //设置连接事件(连接建立/管理)的回调
  16.         _client.setConnectionCallback(std::bind(&DictClient::onConnection,this,std::placeholders::_1));
  17.         //设置连接消息的回调
  18.         _client.setMessageCallback(std::bind(&DictClient::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
  19.         
  20.         //连接服务器
  21.         _client.connect();
  22.         _downlatch.wait();
  23.     }
  24.     bool send(const std::string &msg)
  25.     {
  26.         if(_conn->connected() ==false)
  27.         {
  28.             std::cout<<"连接已经断开,发送数据失败!\n";
  29.             return false;
  30.         }
  31.         _conn->send(msg);
  32.     }
  33. private:
  34.     void onConnection(const muduo::net::TcpConnectionPtr &conn)
  35.     {
  36.         if(conn->connected())
  37.         {
  38.             std::cout<<"连接建立!\n";
  39.             _downlatch.countDown();//计数--,为0时唤醒阻塞
  40.             _conn=conn;
  41.         }
  42.         else
  43.         {
  44.             std::cout<<"连接断开!\n";
  45.             _conn.reset();
  46.         }
  47.     }
  48.     void onMessage(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buf,muduo::Timestamp)
  49.     {
  50.         std::string res = buf->retrieveAllAsString();
  51.         std::cout<< res <<std::endl;
  52.     }
  53. private:
  54.     muduo::net::TcpConnectionPtr _conn;
  55.     muduo::CountDownLatch _downlatch;
  56.     muduo::net::EventLoopThread _loopthrad;
  57.     muduo::net::EventLoop *_baseloop;
  58.     muduo::net::TcpClient _client;
  59. };
  60. int main()
  61. {
  62.     DictClient client("127.0.0.1",9090);
  63.     while(1)
  64.     {
  65.         std::string msg;
  66.         std::cin>>msg;
  67.         client.send(msg);
  68.     }
  69.     return 0;
  70. }
复制代码
2.3 makefile文件

  1. CFLAG= -std=c++11 -I ../../../../build/release-install-cpp11/include/
  2. LFLAG= -L../../../../build/release-install-cpp11/lib  -lmuduo_net -lmuduo_base -pthread
  3. all: server client
  4. server: server.cpp
  5.         g++  $(CFLAG) $^ -o $@ $(LFLAG)
  6. client: client.cpp
  7.         g++  $(CFLAG) $^ -o $@ $(LFLAG)
复制代码
   CFLAG:处理文件中包罗的头文件
   LFLAG:指明链接的库
   三、结语

           到此为止,本文关于从零实现Json-RPC框架第四弹的内容到此竣事了,如有不敷之处,欢迎小伙伴们指出呀!
           关注我 _麦麦_分享更多干货:_麦麦_-CSDN博客
           各人的「关注❤️ + 点赞

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张春

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表