namespace java service.test service Demo { string sayWord(1:string word) }
DemoService.java
package service.test; import org.apache.thrift.TException; import service.test.Demo.Iface; public class DemoService implements Iface { @Override public String sayWord(String word) throws TException { System.out.println("receive " + word); return "hello " + word; } }
MyServer.java
package service.test; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.server.TThreadPoolServer.Args; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransportException; public class MyServer { public void startServer() { try { TServerSocket serverTransport = new TServerSocket(8989); Demo.Processor process = new Demo.Processor(new DemoService()); Factory portFactory = new TBinaryProtocol.Factory(true, true); Args args = new Args(serverTransport); args.processor(process); args.protocolFactory(portFactory); TServer server = new TThreadPoolServer(args); server.serve(); } catch (TTransportException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyServer server = new MyServer(); server.startServer(); } }Client.java
package service.test; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class Client { public void startClient() { TTransport transport; try { transport = new TSocket("localhost", 8989); TProtocol protocol = new TBinaryProtocol(transport); Demo.Client client = new Demo.Client(protocol); transport.open(); System.out.println(client.sayWord("welcome to use thrift...")); transport.close(); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } public static void main(String[] args) { Client client = new Client(); client.startClient(); } }