节俭服务器:检测客户端断开连接(c++库)

Thrift server: detect client disconnections (C++ library)

本文关键字:连接 c++ 断开 客户端 服务器 检测      更新时间:2023-10-16

在运行Thrift服务器时,有必要处理客户端意外断开连接的情况。这可能在服务器处理RPC时发生。如果服务器有阻塞调用,这种情况并不少见,阻塞调用通常用于挂起操作,以便通知客户端异步事件。在任何情况下,这都是一个角落的情况,可能而且确实发生在任何服务器上,清理通常是必要的。

幸运的是,Thrift提供了类TServerEventHandler来挂钩连接/断开回调。这在以前使用c++库和命名管道传输的Thrift版本(我相信是0.8)中是可以工作的。然而,在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
};

如果createContext()和deleteContext()都在客户端连接时调用,而客户端没有断开连接,这是一个错误,应该在Thrift jira中创建一个问题。