【问题标题】:Simple server with Thrift and Qt带有 Thrift 和 Qt 的简单服务器
【发布时间】:2013-04-13 14:12:54
【问题描述】:

我目前的任务是基于 Qt 库创建带有 Thrift IPC 接口的简单服务器。 我已经下载了 thrift、编译、创建了 interface.thrift 文件并生成了存根( --gen cpp )。此外,我已经成功编译了简单的示例,但所有这些东西都没有 Qt。 现在,我需要将 thrift 与 Qt 集成,但 TQTcpServer 需要 Async 处理器! 在存根中我没有找到任何异步处理器(只有 TDispatchProcessor)。

如何将处理器传递给 TQTcpServer ?小例子最好。

TQTcpServer(boost::shared_ptr<QTcpServer> server,
          boost::shared_ptr<TAsyncProcessor> processor,
          boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> protocolFactory,
          QT_PREPEND_NAMESPACE(QObject)* parent = NULL);

【问题讨论】:

    标签: c++ qt ipc thrift


    【解决方案1】:

    我找到了解决方案,可能对其他人有用

    要在 Qt 中使用 Thrift,您需要创建支持异步的 STUB

    thrift --gen cpp:cob_style ./your_name.thrift
    

    将类 your_nameAsyncHandler、your_nameHandler 从生成的 STAB 复制到您的项目

    boost::shared_ptr<QTcpServer> tcp_server_( new QTcpServer() )
    if( !tcp_server_->isListening() && !tcp_server_->listen(QHostAddress::Any, 9090) )
    {
        // throw exception
        return;
    }
    
    shared_ptr<your_nameAsyncHandler> handler(new your_nameAsyncHandler());
    shared_ptr<TAsyncProcessor> processor(new your_nameAsyncProcessor(handler));
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
    
    boost::shared_ptr<apache::thrift::async::TQTcpServer> thrift_server_( new apache::thrift::async::TQTcpServer( tcp_server_, processor, protocolFactory) );
    

    【讨论】:

    • 我整天都在寻找如何让 Async 工作。为什么没有文档。
    【解决方案2】:

    这是我的 main 的样子,非常简单,这都是在 localhost 上运行的。

     int main(int argc, char *argv[]) {
        QCoreApplication a(argc, argv);
    
        boost::shared_ptr<QTcpServer> tcp_server_( new QTcpServer() );
        boost::shared_ptr<UserStorageAsyncHandler> handler(new UserStorageAsyncHandler());
        boost::shared_ptr<TAsyncProcessor> processor(new UserStorageAsyncProcessor(handler));
        boost::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
    
        boost::shared_ptr<apache::thrift::async::TQTcpServer> thrift_server_(
                    new apache::thrift::async::TQTcpServer( tcp_server_, processor, protocolFactory) );
    
        if (!tcp_server_->listen(QHostAddress::Any, 27015)) {
            std::cout << "TCP Server not listening" << std::endl;
            return 1;
        }
        return a.exec();
    }
    

    【讨论】:

    • 看起来不错 ;) 您是否检查 UserStorageAsyncHandler 中的代码是否存在错误或死循环?
    猜你喜欢
    • 2019-07-29
    • 2014-09-26
    • 2011-12-17
    • 1970-01-01
    • 2014-03-02
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多