我想使用Poco::Net::SocketConnector
连接到服务器(例如EchoServer)。但是很遗憾,我不了解SocketConnector
的工作原理。
我的代码:
class ClientHandler
{
public:
ClientHandler(StreamSocket& socket, const
SocketReactor::Ptr& reactor) :
_socket(socket),
_reactor(reactor),
_or(*this, &ClientHandler::onReadable),
_ow(*this, &ClientHandler::onWritable),
_ot(*this, &ClientHandler::onTimeout),
{
_reactor->addEventHandler(_socket, _or);
_reactor->addEventHandler(_socket, _ow);
_reactor->addEventHandler(_socket, _ot);
}
~ClientHandler()
{
std::cout << "~ClientHandler" << std::endl;
}
void onReadable(ReadableNotification* pNf)
{
pNf->release();
char buffer[32];
int n = _socket.receiveBytes(buffer, sizeof(buffer));
if (n == 0)
return;
for (size_t i = 0; i < n; ++i)
{
std::cout << (int)buffer[i] << " ";
}
std::cout << std::endl;
}
void onWritable(WritableNotification* pNf)
{
pNf->release();
UInt8 data[] = { 0x01, 0x02, 0x03 };
_socket.sendBytes(data, 3);
}
private:
StreamSocket _socket;
SocketReactor::Ptr _reactor;
Observer<ClientHandler, ReadableNotification> _or;
Observer<ClientHandler, WritableNotification> _ow;
Observer<ClientHandler, TimeoutNotification> _ot;
};
用法:
EchoServer echoServer;
SocketAddress sa("localhost", echoServer.port());
SocketConnector<ClientHandler> connector(sa, reactor);
Poco::Thread thread;
thread.start(reactor);
Poco::Thread::sleep(1000 * 3);
reactor->stop();
thread.join();
我连接成功,但是我的问题是我不了解如何才能访问ClientHandler
来发送除1 2 3
之外的其他内容。
第二个问题:ClientHandler
在哪里被摧毁?