博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Poco Reactor Demo
阅读量:4957 次
发布时间:2019-06-12

本文共 2670 字,大约阅读时间需要 8 分钟。

ReactorTest.cc

#include "Poco/Net/SocketReactor.h"#include "Poco/Net/SocketNotification.h"#include "Poco/Net/SocketConnector.h"#include "Poco/Net/SocketAcceptor.h"#include "Poco/Net/StreamSocket.h"#include "Poco/Net/ServerSocket.h"#include "Poco/Net/SocketAddress.h"#include "Poco/Observer.h"#include 
#include
using Poco::Net::SocketReactor;using Poco::Net::SocketConnector;using Poco::Net::SocketAcceptor;using Poco::Net::StreamSocket;using Poco::Net::ServerSocket;using Poco::Net::SocketAddress;using Poco::Net::SocketNotification;using Poco::Net::ReadableNotification;using Poco::Net::WritableNotification;using Poco::Net::TimeoutNotification;using Poco::Net::ShutdownNotification;using Poco::Observer;class MyHandler { public: MyHandler(StreamSocket& socket, SocketReactor& reactor): _socket(socket), _reactor(reactor) { _peerAddress = socket.peerAddress().toString(); std::cout << "connection from " << _peerAddress << " ..." << std::endl; _reactor.addEventHandler(_socket, Observer
(*this, &MyHandler::onReadable)); } ~MyHandler() { std::cout << _peerAddress << " disconnected ..." << std::endl; _reactor.removeEventHandler(_socket, Observer
(*this, &MyHandler::onReadable)); } void onReadable(ReadableNotification* pNf) { pNf->release(); char buffer[8]; int n = _socket.receiveBytes(buffer, sizeof(buffer)); if (n > 0) { _socket.sendBytes(buffer, n); _socket.sendBytes("\n", 1); std::cout << "receive buffer from " << _peerAddress << " : " << std::string(buffer, n) << std::endl; } else { _socket.shutdownSend(); delete this; } } private: StreamSocket _socket; std::string _peerAddress; SocketReactor& _reactor;};// === FUNCTION ======================================================================// Name: main// Description: main function// ===================================================================================== intmain ( int argc, char *argv[] ){ unsigned short port = 7070; ServerSocket serverSocket(port); SocketReactor reactor; SocketAcceptor
acceptor(serverSocket, reactor); std::cout << "\nReactor: \"" << argv[0] << "\" starting..." << std::endl; reactor.run(); std::cout << "\nReactor: \"" << argv[0] << "\" stopped." << std::endl; return EXIT_SUCCESS;} // ---------- end of function main ----------

结果

转载于:https://www.cnblogs.com/Leo-Forest/archive/2013/05/16/3082218.html

你可能感兴趣的文章