0

Background: I have many small c++ programs that all use the same static library. I'm now implementing thrift as a middle layer so that I can run the small c++ programs on a different computer from the static library. I can't change the c++ programs, so I am making a "fake" static library that looks like the original, but is actually a thrift client that calls the real static library.

Issue: How can I make the static library so that the c++ programs will automatically open the socket when it opens the library, and closes the socket when the program exits??

Usually thrift clients use a main method that opens the socket in the beginning and closes it in the end. I can have the library check if the socket is open before every method call, but I don't know how to close the socket. Is there any problem with leaving it open?

4

1 回答 1

1

一种方法可能是在您的库中使用单个本地静态实例创建一个 C++ 类。由于实例将在第一次调用时构建并在卸载时销毁,因此您可以使用构造函数/析构函数进行连接和断开连接,如下所示:

#include <boost/shared_ptr.hpp>
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include "gen-cpp/mySvc.h"                  

using namespace apache::thrift::transport;  
using namespace apache::thrift::protocol;   

class ThriftProxy {
public:
    ThriftProxy() :
        trans(new TSocket("myhost", 8585)),
        proto(new TBinaryProtocol(trans)),
        client_(proto)
    {
        trans->open();
    }

    ~ThriftProxy()
    {
        trans->close();
    }

    static mySvcClient & client() 
    {
        static ThriftProxy proxy;
        return proxy.client_;
    }    

private:
    boost::shared_ptr<TSocket> trans;
    boost::shared_ptr<TProtocol> proto;
    mySvcClient client_;
};

然后,您的 lib 中的函数可以使用 ThriftProxy::client() 方法调用 Apache Thrift 服务器:

int exportedFunc(int i) {
    return ThriftProxy::client().myRPCFunc(i);
}

注意:在大多数情况下,将 TBufferedTransport 或 TFramedTransport 添加到 I/O 堆栈是减少对网络的小型写入的好主意。此处省略以保持示例简单。

于 2013-07-12T21:13:37.193 回答