节俭服务器:检测客户端断开(C ++库)(Thrift server: detect client

2019-10-20 03:13发布

当运行一个节俭的服务器,这是必要的处理,其中客户端意外断开连接的情况。 当服务器处理的RPC可能发生这种情况。 这是常有的事,如果服务器有一个阻塞调用它通常以异步事件通知客户用来挂起的操作。 在任何情况下,它是可以和它在任何服务器上发生和清理往往是必要的一个角落里的情况。

幸运的节俭提供了类TServerEventHandler挂接到连接/断开回调。 这用于储蓄的以前版本一起使用(0.8,我相信)使用C ++库和命名管道传输。 然而,在节俭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
};

Answer 1:

如果的createContext()和deleteContext()都被称为在客户端无需在客户端断开连接,这是一个错误,应该在旧货JIRA所造成的问题。



文章来源: Thrift server: detect client disconnections (C++ library)