我最终什么事是一种使用不同的方法,因为TCPSERVER是一个不同的野兽一起。在发布here的示例之后,我结束了一个继承自ServerApplication的类以及一个实质上连接处理程序由SocketReactor构成的类。
Deamonizer头:
class Daemon : public ServerApplication
{
public:
Daemon();
/// @Brief The main loop of the daemon, everything must take place here
int main();
};
Deamonizer实现:
int Daemon::main()
{
// Server Socket
ServerSocket svs(2222);
// Reactor-Notifier
SocketReactor reactor;
Poco::Timespan timeout(2000000); // 2Sec
reactor.setTimeout(timeout);
// Server-Acceptor
SocketAcceptor<ConnectionHandler> acceptor(svs, reactor);
// Threaded Reactor
Thread thread;
thread.start(reactor);
// Wait for CTRL+C
waitForTerminationRequest();
// Stop Reactor
reactor.stop();
thread.join();
return Application::EXIT_OK;
}
处理程序类可以是任何东西,只要它具有符合构造函数(请参阅本波科:: NET文档)。 在我的情况,头看起来是这样的:
class ConnectionHandler
{
public:
/**
* @Brief Constructor of the Connection Handler
* @Note Each object is unique to an accepted connection
* @Param SteamSocket is the socket accepting the connections
* @See SocketAcceptor http://pocoproject.org/docs/Poco.Net.SocketAcceptor.html
* @Param SocketReactor is the reacting engine (threaded) which creates notifications about the socket
*/
ConnectionHandler(StreamSocket &, SocketReactor &);
/**
* @Brief Destructor
*/
~ConnectionHandler();
/**
* @Brief Event Handler when Socket becomes Readable, i.e: there is data waiting to be read
*/
void onSocketReadable(const AutoPtr<ReadableNotification>& pNf);
/**
* @Brief Event Handler when Socket was written, i.e: confirmation of data sent away (not received by client)
*/
void onSocketWritable(const AutoPtr<WritableNotification>& pNf);
/**
* @Brief Event Handler when Socket was shutdown on the remote/peer side
*/
void onSocketShutdown(const AutoPtr<ShutdownNotification>& pNf);
/**
* @Brief Event Handler when Socket throws an error
*/
void onSocketError(const AutoPtr<ErrorNotification>& pNf);
/**
* @Brief Event Handler when Socket times-out
*/
void onSocketTimeout(const AutoPtr<TimeoutNotification>& pNf);
private:
/**
* @Brief Read bytes from the socket, depending on available bytes on socket
*/
void readBytes();
/**
* @Brief Send message to the socket
* @Param std::string is the message (null terminated)
*/
void sendMessage(std::string);
/// Stream Socket
StreamSocket _socket;
/// Socket Reactor-Notifier
SocketReactor& _reactor;
/// Received Data Buffer
std::vector<char *> in_buffer;
};
你如何实现处理是你的,前提是你需要做的是注册类方法,它处理事件,像这样的唯一的事情:
_reactor.addEventHandler(_socket,NObserver<ConnectionHandler, ReadableNotification>(*this, &ConnectionHandler::onSocketReadable));
_reactor.addEventHandler(_socket,NObserver<ConnectionHandler, ShutdownNotification>(*this, &ConnectionHandler::onSocketShutdown));
_reactor.addEventHandler(_socket,NObserver<ConnectionHandler, ErrorNotification>(*this, &ConnectionHandler::onSocketError));
_reactor.addEventHandler(_socket,NObserver<ConnectionHandler, TimeoutNotification>(*this, &ConnectionHandler::onSocketTimeout));
总而言之,两个类,几行代码,简单而干净。绝对开始爱Poco图书馆! :)
尼斯反应堆:)谢谢亚历克斯 –