Search code examples
javapythonthrift

Connection of thrift-client will only be successful after the first starting of this client


It's the first time after restarting my java thrift client that can be useful. And then it has shown a socket timeout. Throwing an exception:

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

Here is my python thrift server;

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")

Here is my Java thrift client:

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

Solution

  • I fixed this issue because I've used 'new Client', this will prevent the next connection. so I changed the code to this:

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