本文主要是介绍基于handy的聊天室,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
handy是c++的网络库,其简单易用,容易上手。
github地址:
https://github.com/yedf/handyhttps://github.com/yedf/handy
以下便实现了一个聊天室,任意一个人发送的数据会被转发给其他所有人,参考的是示例中的chat.cc,并做了一些修改,代码如下:
#include <handy/handy.h>
#include <map>using namespace std;
using namespace handy;int main(int argc, const char *argv[]) {setloglevel("TRACE");//连接管理容器map<intptr_t, TcpConnPtr> users; //生命周期比连接更长,必须放在Base前EventBase base;Signal::signal(SIGINT, [&] { base.exit(); });int userid = 1;//监听8888端口TcpServerPtr chat = TcpServer::startServer(&base, "", 8888);exitif(chat == NULL, "start tcpserver failed");chat->onConnCreate([&] {TcpConnPtr con(new TcpConn);//客户端连接与断开事件con->onState([&](const TcpConnPtr &con) {if (con->getState() == TcpConn::Connected) {con->context<int>() = userid;users[userid] = con;userid++;} else if (con->getState() == TcpConn::Closed) {users.erase(con->context<int>());}});//客户端读事件这里不用onMsg,onMsg封装了整包检验功能,这里读原始数据con->onRead([&](const TcpConnPtr &con) {int cid = con->context<int>();//客户端计数int sended = 0;//转发给其他所有用户for (auto &pc : users) {if (pc.first != cid) {sended++;//以下代码存在问题,读缓冲区会被清空// pc.second->send(con->getInput());pc.second->send(con->getInput().data(),con->getInput().size());}}//清空读缓冲区con->getInput().clear();});return con;});base.loop();info("program exited");return 0;
}
这篇关于基于handy的聊天室的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!