Thrift服务器:检测客户端断开连接(C ++库)

时间:2014-05-13 20:40:22

标签: c++ client-server thrift thrift-protocol

运行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
};

1 个答案:

答案 0 :(得分:1)

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