thrift-client的连接仅在该客户端首次启动后才能成功

时间:2018-11-04 05:33:40

标签: java python thrift

这是重启我的Java thrift客户端后第一次有用的方法。然后它显示了套接字超时。引发异常:

org.apache.thrift.transport.TTransportException: java.net.SocketTimeoutException: Read timed out

这是我的python旧版服务器;

if __name__ == '__main__':
 handler = MessageServiceHandler()
    processor = MessageService.Processor(handler)
    transport = TSocket.TServerSocket(host="127.0.0.1", port=9090)
    tFactory = TTransport.TFramedTransportFactory()
    pFactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tFactory, pFactory)
    print("python thrift message service start")
    server.serve()
    print("python thrift message service exit")

这是我的Java节俭客户端:

   public MessageService.Client getMessageService() {
        TSocket socket = new TSocket("localhost", 9090, 3000);
        TTransport transport = new TFramedTransport(socket);
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        TProtocol protocol = new TBinaryProtocol(transport);
        MessageService.Client client = new MessageService.Client(protocol); 
        return client;
    }

1 个答案:

答案 0 :(得分:0)

我已解决此问题,因为我使用了“新客户端”,这将阻止下一次连接。所以我将代码更改为此:

MessageService.Client messageServiceClient;
public MessageService.Client getMessageService() {
   if(messageServiceClient!=null){ 
       return messageServiceClient;
   }
   TSocket socket = new TSocket("localhost", 9090, 3000);
   TTransport transport = new TFramedTransport(socket);
   try {
       transport.open();
   } catch (TTransportException e) {
       e.printStackTrace();
   }
   TProtocol protocol = new TBinaryProtocol(transport);
   messageServiceClient = new MessageService.Client(protocol); 
   return messageServiceClient;
}