thrift服务端与客户端代码

服务端代码:

public class HelloServerDemo {

	public void startServer() {
		try {
			/**
             * 简单的单线程服务模型
             */
            // TServer.Args tArgs = new TServer.Args(new TServerSocket(8090));
            // TProcessor tprocessor = new HelloWorldService.Processor(new
            // HelloWorldImpl());
            // tArgs.processor(tprocessor);
            // tArgs.protocolFactory(new TBinaryProtocol.Factory());
            // TServer server = new TSimpleServer(tArgs);
            // server.serve();

            /**
             * 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。
             */
            TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args(new TServerSocket(SERVER_PORT));
            TProcessor tprocessor = new HelloWorldService.Processor(new HelloWorldImpl());
            ttpsArgs.processor(tprocessor);
            ttpsArgs.protocolFactory(new TBinaryProtocol.Factory());
            TServer server = new TThreadPoolServer(ttpsArgs);
            System.out.println("server startup");
            server.serve();// 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloServerDemo server = new HelloServerDemo();
		server.startServer();
	}

}

客户端代码:

public class HelloClientDemo {
	public void startClient(String userName) {
		TTransport tTransport = null;
		try {
			tTransport = new TSocket("localhost", 8090, 30000);
			// 协议要和服务端一致
			TProtocol protocol = new TBinaryProtocol(tTransport);
			Client client = new Client(protocol);
			tTransport.open();
			client.sayHello(userName);
		} catch (TTransportException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		} finally {
			if (null != tTransport) {
				tTransport.close();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloClientDemo client = new HelloClientDemo();
		client.startClient("heisenberg");
	}

}


你可能感兴趣的:(thrift服务端与客户端代码)