运行 Thrift 服务器时,有必要处理客户端意外断开连接的情况。这可能在服务器处理 RPC 时发生。如果服务器有一个阻塞调用,该调用通常用于挂起操作以通知客户端异步事件,则这种情况并不少见。无论如何,这是一个极端情况,可以而且确实会在任何服务器上发生,并且通常需要进行清理。
幸运的是 Thrift 提供了类 TServerEventHandler 来挂钩连接/断开回调。这曾经在 Thrift 的早期版本(我相信是 0.8)中使用 C++ 库和命名管道传输。然而,在 Thrift 0.9.1 中,createContext() 和 deleteContext() 回调都会在客户端连接时立即触发。不再在客户端断开连接时触发。有没有一种新的方法来检测客户端断开连接?
代码片段:
//============================================================================
//Code snippet where the server is instantiated and started. This may
//or may not be syntactically correct.
//The event handler class is derived from TServerEventHandler.
//
{
boost::shared_ptr<MyHandler> handler(new MyHandler());
boost::shared_ptr<TProcessor> processor(new MyProcessor(handler));
boost::shared_ptr<TServerTransport> serverTransport(new TPipeServer("MyPipeName"));
boost::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
boost::shared_ptr<TServer> server(new TSimpleServer(processor, transport, tfactory, pfactory));
boost::shared_ptr<SampleEventHandler> EventHandler(new SampleEventHandler());
server->setServerEventHandler(EventHandler);
server->serve();
}
//============================================================================
//Sample event callbacks triggered by the server when something interesting
//happens with the client.
//Create an overload of TServerEventHandler specific to your needs and
//implement the necessary methods.
//
class SampleEventHandler : public server::TServerEventHandler {
public:
SampleEventHandler() :
NumClients_(0) //Initialize example member
{}
//Called before the server begins -
//virtual void preServe() {}
//createContext may return a user-defined context to aid in cleaning
//up client connections upon disconnection. This example dispenses
//with contextual information and returns NULL.
virtual void* createContext(boost::shared_ptr<protocol::TProtocol> input, boost::shared_ptr<protocol::TProtocol> output)
{
printf("SampleEventHandler callback: Client connected (total %d)\n", ++NumClients_);
return NULL;
}
//Called when a client has disconnected, either naturally or by error.
virtual void deleteContext(void* serverContext, boost::shared_ptr<protocol::TProtocol>input, boost::shared_ptr<protocol::TProtocol>output)
{
printf("SampleEventHandler callback: Client disconnected (total %d)\n", --NumClients_);
}
//Called when a client is about to call the processor -
//virtual void processContext(void* serverContext,
boost::shared_ptr<TTransport> transport) {}
protected:
uint32_t NumClients_; //Example member
};