一、前言
在本文将会为大家介绍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::enable_shared_from_this<tcpconnection>
{
public:
/// constructs a tcpconnection with a connected sockfd
///
/// user should not create this object.
tcpconnection(eventloop* loop,
const string& name,
int sockfd,
const inetaddress& localaddr,
const inetaddress& peeraddr);
bool connected() const { return state_ == kconnected; }
bool disconnected() const { return state_ == kdisconnected; }
void send(string&& message); // c++11
void send(const void* message, int len);
void send(const stringpiece& message);
// void send(buffer&& message); // c++11
void send(buffer* message); // this one will swap data
void shutdown(); // not thread safe, no simultaneous calling
void setcontext(const boost::any& context)
{ context_ = context; }
const boost::any& getcontext() const
{ return context_; }
boost::any* getmutablecontext()
{ return &context_; }
void setconnectioncallback(const connectioncallback& cb)
{ connectioncallback_ = cb; }
void setmessagecallback(const messagecallback& cb)
{ messagecallback_ = cb; }
private:
enum statee { kdisconnected, kconnecting, kconnected, kdisconnecting };
eventloop* loop_;
connectioncallback connectioncallback_;
messagecallback messagecallback_;
writecompletecallback writecompletecallback_;
boost::any context_;
};在tcpconnection与连接相关的类常用函数的有:
①判断当前的连接情况——connected() / disconnected()
②向连接的远端服务端发送消息——send()
1.4 tcpclient类基础介绍
● tcpclient
tcpclient(eventloop* loop,const inetaddress& serveraddr, const string& namearg);
对于tcpclient的构造需要传递loop指针进行事件监控,inetaddress来指明服务端的ip和port,namearg则是指明tcpclient的命名
●void connect()
调用该函数,tcpclient则会向已经设置好的远端服务器进行连接
●void disconnect()
调用该函数,tcpclient则会取消与远端服务器的连接
●void setconnectioncallback(connectioncallback cb)
/// 连接服务器成功时的回调函数
void setconnectioncallback(connectioncallback cb)
{ connectioncallback_ = std::move(cb); }●void setmessagecallback(messagecallback cb)
/// 收到服务器发送的消息时的回调函数
void setmessagecallback(messagecallback cb)
{ messagecallback_ = std::move(cb); }1.5 countdownlatch 类
因为 muduo 库不管是服务端还是客⼾端都是异步操作, 对于客⼾端来说如果我们在连接还没有完全建⽴成功的时候发送数据,这是不被允许的。 因此我们可以使⽤内置的countdownlatch 类进⾏同步控制。具体的思路就是给计数器count一个初值,比如说1,当连接建立成功的时候,我们将该值减少为0,才进行loop的事件监控,否则就一直处于阻塞等待连接的状态,避免client还没有建立连接成功,就进入事件的监控,这是不符合逻辑的。
class countdownlatch : noncopyable
{
public:
explicit countdownlatch(int count);
void wait(){
mutexlockguard lock(mutex_);
while (count_ > 0)
{
condition_.wait();
}
}
void countdown(){
mutexlockguard lock(mutex_);--count_;
if (count_ == 0)
{
condition_.notifyall();
}
}
int getcount() const;
private:
mutable mutexlock mutex_;
condition condition_ guarded_by(mutex_);
int count_ guarded_by(mutex_);
};1.6 buffer类基础介绍
class buffer : public muduo::copyable
{
public:
static const size_t kcheapprepend = 8;
static const size_t kinitialsize = 1024;
explicit buffer(size_t initialsize = kinitialsize)
: buffer_(kcheapprepend + initialsize),
readerindex_(kcheapprepend),
writerindex_(kcheapprepend);
void swap(buffer& rhs)
size_t readablebytes() const
size_t writablebytes() const
const char* peek() const
const char* findeol() const
const char* findeol(const char* start) const
void retrieve(size_t len)
void retrieveint64()
void retrieveint32()
void retrieveint16()
void retrieveint8()
string retrieveallasstring()
string retrieveasstring(size_t len)
void append(const stringpiece& str)
void append(const char* /*restrict*/ data, size_t len)
void append(const void* /*restrict*/ data, size_t len)
char* beginwrite()
const char* beginwrite() const
void haswritten(size_t len)
void appendint64(int64_t x)
void appendint32(int32_t x)
void appendint16(int16_t x)
void appendint8(int8_t x)
int64_t readint64()
int32_t readint32()
int16_t readint16()
int8_t readint8()
int64_t peekint64() const
int32_t peekint32() const
int16_t peekint16() const
int8_t peekint8() const
void prependint64(int64_t x)
void prependint32(int32_t x)
void prependint16(int16_t x)
void prependint8(int8_t x)
void prepend(const void* /*restrict*/ data, size_t len)
private:
std::vector<char> buffer_;
size_t readerindex_;
size_t writerindex_;
static const char kcrlf[];
};在buffer类中,我们这次用到的接口是retrieveallasstring(),由于我们字典翻译的请求间隔时间比较长,因此默认缓冲区里的数据就是一次完整的翻译请求,所以我们就使用retrieveallasstring()接口将缓冲区的数据全部读作为一次完整的请求
2. muduo库英译汉服务
2.1 英译汉tcp服务器
/*
实现一个翻译服务器,客户端发送过来一个英语单词,返回一个汉语词语
*/
#include <muduo/net/tcpserver.h>
#include <muduo/net/eventloop.h>
#include <muduo/net/tcpconnection.h>
#include <muduo/net/tcpclient.h>
#include <muduo/net/buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>
class dicserver{
public:
dicserver(int port)
:_server(&_baseloop,
muduo::net::inetaddress("0.0.0.0",port),
"dicserver",muduo::net::tcpserver::option::kreuseport)
{
//设置连接事件(连接建立/管理)的回调
_server.setconnectioncallback(std::bind(&dicserver::onconnection,this,std::placeholders::_1));
//设置连接消息的回调
_server.setmessagecallback(std::bind(&dicserver::onmessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
}
void start()
{
_server.start(); //先开始监听
_baseloop.loop(); //再开始死循环事件监控
}
private:
void onconnection(const muduo::net::tcpconnectionptr &conn)
{
if(conn->connected())
std::cout<<"连接建立!\n";
else
std::cout<<"连接断开!\n";
}
void onmessage(const muduo::net::tcpconnectionptr &conn,muduo::net::buffer *buf,muduo::timestamp)
{
static std::unordered_map<std::string,std::string> dict_map={
{"hello","你好"},
{"world","世界"},
{"worker","打工人"}
};
std::string msg=buf->retrieveallasstring();
std::string res;
auto it=dict_map.find(msg);
if(it != dict_map.end())
res=it->second;
else
res="未知单词!";
conn->send(res);
}
public:
muduo::net::eventloop _baseloop;
muduo::net::tcpserver _server;
};
int main()
{
dicserver server(9090);
server.start();
return 0;
}2.2 英译汉客户端
#include <muduo/net/tcpclient.h>
#include <muduo/net/eventloop.h>
#include <muduo/net/eventloopthread.h>
#include <muduo/net/tcpclient.h>
#include <muduo/net/buffer.h>
#include <iostream>
#include <string>
class dictclient{
public:
dictclient(const std::string &sip,int sport)
:_baseloop(_loopthrad.startloop())
,_downlatch(1) //初始化计数器为1,只有为0时才会唤醒
,_client(_baseloop,muduo::net::inetaddress(sip,sport),"dicclient")
{
//设置连接事件(连接建立/管理)的回调
_client.setconnectioncallback(std::bind(&dictclient::onconnection,this,std::placeholders::_1));
//设置连接消息的回调
_client.setmessagecallback(std::bind(&dictclient::onmessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
//连接服务器
_client.connect();
_downlatch.wait();
}
bool send(const std::string &msg)
{
if(_conn->connected() ==false)
{
std::cout<<"连接已经断开,发送数据失败!\n";
return false;
}
_conn->send(msg);
}
private:
void onconnection(const muduo::net::tcpconnectionptr &conn)
{
if(conn->connected())
{
std::cout<<"连接建立!\n";
_downlatch.countdown();//计数--,为0时唤醒阻塞
_conn=conn;
}
else
{
std::cout<<"连接断开!\n";
_conn.reset();
}
}
void onmessage(const muduo::net::tcpconnectionptr &conn,muduo::net::buffer *buf,muduo::timestamp)
{
std::string res = buf->retrieveallasstring();
std::cout<< res <<std::endl;
}
private:
muduo::net::tcpconnectionptr _conn;
muduo::countdownlatch _downlatch;
muduo::net::eventloopthread _loopthrad;
muduo::net::eventloop *_baseloop;
muduo::net::tcpclient _client;
};
int main()
{
dictclient client("127.0.0.1",9090);
while(1)
{
std::string msg;
std::cin>>msg;
client.send(msg);
}
return 0;
}2.3 makefile文件
cflag= -std=c++11 -i ../../../../build/release-install-cpp11/include/ lflag= -l../../../../build/release-install-cpp11/lib -lmuduo_net -lmuduo_base -pthread all: server client server: server.cpp g++ $(cflag) $^ -o $@ $(lflag) client: client.cpp g++ $(cflag) $^ -o $@ $(lflag)
cflag:处理文件中包含的头文件
lflag:指明链接的库
三、结语
以上就是c++使用muduo库实现英译汉功能的详细内容,更多关于c++ muduo英译汉的资料请关注代码网其它相关文章!
发表评论