moduo windows下简单使用

moduo windows下简单使用,第1张

本人在windows下学习该库,使用的是GitHub - kevin-gjm/muduo-win: muduo in windows

linux下可以使用https://github.com/chenshuo/muduo.git

编译:

设置main的入口:

 

运行即打开了 tcp_server。

测试连接  

 进入命令模式:快捷键  :ctrl + ]

  测试代码:

#include "TcpServer.h"
#include "logging.h"
#include 
#include 
using namespace calm;
using namespace calm::net;

class EchoServer
{
public:
	EchoServer(EventLoop* loop,InetAddress& listenAddr)
		:loop_(loop),
		server_(loop,listenAddr,"EchoServer")
	{
	    //给服务器注册用户建立断开连接的回调
		server_.setConnectionCallback(std::bind(&EchoServer::onConnection,this,std::placeholders::_1));
		//给服务器注册用户可读写事件回调
		server_.setMessageCallback(std::bind(&EchoServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
	
		server_.setThreadNum(3);
	}
	void start()
	{
		server_.start();
	}
private:
	void onConnection(const TcpConnectionPtr& conn)
	{
		LOG_INFO << conn->peerAddress().toIpPort() << " -> "
			<< conn->localAddress().toIpPort() << " is "
			<< (conn->connected() ? "UP" : "DOWN");
		conn->send("hello calm\n");
	}
	void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time)
	{
		string msg(buf->retrieveAllAsString());
		//LOG_INFO << conn->name() << " recv " << msg.size() << " bytes at " << time.toString();
		std::cout << "receive: " << msg  << "\n";
 		if (msg == "exit\n")
		{
			conn->send("bye\n");
			conn->shutdown();//关闭写端 
		}
		if (msg == "quit\n")
		{
			loop_->quit();
		}
		conn->send(msg);
	}
	EventLoop* loop_;
	TcpServer server_;
};//end EchoServer

int main()
{
	LOG_INFO << "ThreadId = " << getCurrentThreadId();
	EventLoop loop;
	InetAddress listenAddr("127.0.0.1", 8080);
	EchoServer server(&loop, listenAddr);
	server.start();

	loop.loop();
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1295557.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存