#include<muduo/net/TcpServer.h>
#include<muduo/net/EventLoop.h>
#include<string>
#include<iostream>
#include<functional>
using namespace muduo;
using namespace muduo::net;
using namespace std;
class ChatServer
{
public:ChatServer(EventLoop* loop, const InetAddress& listenAddr,const string& nameArg):_server(loop,listenAddr,nameArg),_loop(loop){
_server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));_server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));_server.setThreadNum(4);}void start(){
_server.start();}
private:void onConnection(const TcpConnectionPtr& conn){
if(conn->connected()){
cout << conn->peerAddress().toIpPort() << "->" << conn->localAddress().toIpPort() << "STATE :online" <<endl;}else{
cout << conn->peerAddress().toIpPort() << "->" << conn->localAddress().toIpPort() << "STATE :offline" <<endl;conn->shutdown();_loop->quit();}}void onMessage(const TcpConnectionPtr& conn,Buffer* buffer,Timestamp time){
string buf = buffer->retrieveAllAsString();cout << "recv data" << buf << "Time:" << time.toString() << endl;conn->send(buf);}TcpServer _server; EventLoop* _loop;
};int main()
{
EventLoop loop;InetAddress addr("127.0.0.1",6000);ChatServer server(&loop,addr,"Charserver");server.start();loop.loop();return 0;
}
调试文件
ctrl+shift+b
task.json
{
"tasks": [{
"type": "shell","label": "g++ build active file","command": "/usr/bin/g++","args": ["-g","-std=c++11","${file}","-o","${fileDirname}/${fileBasenameNoExtension}","-lmuduo_net","-lmuduo_base","-lpthread"],"options": {
"cwd": "/usr/bin"},"problemMatcher": ["$gcc"],"group": "build"}],"version": "2.0.0"
}