Poco Reactor Demo
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 <iostream> #include <cstdlib> 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<MyHandler, ReadableNotification>(*this, &MyHandler::onReadable)); } ~MyHandler() { std::cout << _peerAddress << " disconnected ..." << std::endl; _reactor.removeEventHandler(_socket, Observer<MyHandler, ReadableNotification>(*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 // ===================================================================================== int main ( int argc, char *argv[] ) { unsigned short port = 7070; ServerSocket serverSocket(port); SocketReactor reactor; SocketAcceptor<MyHandler> 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 ----------
结果