test13.cc revision a1bde736
1a1bde736SShuo Chen#include "EventLoop.h" 2a1bde736SShuo Chen#include "InetAddress.h" 3a1bde736SShuo Chen#include "TcpClient.h" 4a1bde736SShuo Chen 5a1bde736SShuo Chen#include "logging/Logging.h" 6a1bde736SShuo Chen 7a1bde736SShuo Chen#include <boost/bind.hpp> 8a1bde736SShuo Chen 9a1bde736SShuo Chen#include <utility> 10a1bde736SShuo Chen 11a1bde736SShuo Chen#include <stdio.h> 12a1bde736SShuo Chen#include <unistd.h> 13a1bde736SShuo Chen 14a1bde736SShuo Chenstd::string message = "Hello\n"; 15a1bde736SShuo Chen 16a1bde736SShuo Chenvoid onConnection(const muduo::TcpConnectionPtr& conn) 17a1bde736SShuo Chen{ 18a1bde736SShuo Chen if (conn->connected()) 19a1bde736SShuo Chen { 20a1bde736SShuo Chen printf("onConnection(): new connection [%s] from %s\n", 21a1bde736SShuo Chen conn->name().c_str(), 22a1bde736SShuo Chen conn->peerAddress().toHostPort().c_str()); 23a1bde736SShuo Chen conn->send(message); 24a1bde736SShuo Chen } 25a1bde736SShuo Chen else 26a1bde736SShuo Chen { 27a1bde736SShuo Chen printf("onConnection(): connection [%s] is down\n", 28a1bde736SShuo Chen conn->name().c_str()); 29a1bde736SShuo Chen } 30a1bde736SShuo Chen} 31a1bde736SShuo Chen 32a1bde736SShuo Chenvoid onMessage(const muduo::TcpConnectionPtr& conn, 33a1bde736SShuo Chen muduo::Buffer* buf, 34a1bde736SShuo Chen muduo::Timestamp receiveTime) 35a1bde736SShuo Chen{ 36a1bde736SShuo Chen printf("onMessage(): received %zd bytes from connection [%s] at %s\n", 37a1bde736SShuo Chen buf->readableBytes(), 38a1bde736SShuo Chen conn->name().c_str(), 39a1bde736SShuo Chen receiveTime.toFormattedString().c_str()); 40a1bde736SShuo Chen 41a1bde736SShuo Chen printf("onMessage(): [%s]\n", buf->retrieveAsString().c_str()); 42a1bde736SShuo Chen} 43a1bde736SShuo Chen 44a1bde736SShuo Chenint main() 45a1bde736SShuo Chen{ 46a1bde736SShuo Chen muduo::EventLoop loop; 47a1bde736SShuo Chen muduo::InetAddress serverAddr("localhost", 9981); 48a1bde736SShuo Chen muduo::TcpClient client(&loop, serverAddr); 49a1bde736SShuo Chen 50a1bde736SShuo Chen client.setConnectionCallback(onConnection); 51a1bde736SShuo Chen client.setMessageCallback(onMessage); 52a1bde736SShuo Chen client.enableRetry(); 53a1bde736SShuo Chen client.connect(); 54a1bde736SShuo Chen loop.loop(); 55a1bde736SShuo Chen} 56a1bde736SShuo Chen 57