muduo/net/TcpServer.h
muduo/net/TcpServer.cc
使用命令 nc 127.0.0.1 8888 作为客户端连接上开启的服务器
#include <muduo/net/TcpServer.h> #include <muduo/net/EventLoop.h> #include <muduo/net/InetAddress.h> #include <stdio.h> using namespace muduo; using namespace muduo::net; void onConnection(const TcpConnectionPtr& conn) { if (conn->connected()) { printf("onConnection(): new connection [%s] from %s\n", conn->name().c_str(), conn->peerAddress().toIpPort().c_str()); } else { printf("onConnection(): connection [%s] is down\n", conn->name().c_str()); } } void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) { string msg(buf->retrieveAllAsString()); printf("onMessage(): received %zd bytes from connection [%s]\n", msg.size(), conn->name().c_str()); } int main() { printf("main(): pid = %d\n", getpid()); InetAddress listenAddr(8888);//端口号 EventLoop loop; TcpServer server(&loop, listenAddr, "TestServer"); server.setConnectionCallback(onConnection); server.setMessageCallback(onMessage); server.start(); loop.loop(); }