PS:如果服务器和客户端通信。可以通过WebService,不过这种有点大费劲,太重了。可以通过socket
package cn.itcast.bigdata.socket; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; public class ServiceServer { public static void main(String[] args) throws Exception { // 创建一个serversocket,绑定到本机的8899端口上 ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", 8899)); // 接受客户端的连接请求;accept是一个阻塞方法,会一直等待,到有客户端请求连接才返回 while (true) { Socket socket = server.accept(); new Thread(new ServiceServerTask(socket)).start(); } } }
package cn.itcast.bigdata.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServiceServerTask implements Runnable{ Socket socket ; InputStream in=null; OutputStream out = null; public ServiceServerTask(Socket socket) { this.socket = socket; } //业务逻辑:跟客户端进行数据交互 @Override public void run() { try { //从socket连接中获取到与client之间的网络通信输入输出流 in = socket.getInputStream(); out = socket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); //从网络通信输入流中读取客户端发送过来的数据 //注意:socketinputstream的读数据的方法都是阻塞的 String param = br.readLine(); /** * 作业: * 将以下业务调用逻辑写成更加通用的:可以根据客户端发过来的调用类名、调用方法名、调用该参数来灵活调用 * * 《反射》 * */ GetDataServiceImpl getDataServiceImpl = new GetDataServiceImpl(); String result = getDataServiceImpl.getData(param); //将调用结果写到sokect的输出流中,以发送给客户端 PrintWriter pw = new PrintWriter(out); pw.println(result); pw.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try { in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
//客户端
package cn.itcast.bigdata.socket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServiceClient { public static void main(String[] args) throws Exception { /*ServiceIterface service = ProxyUtils.getProxy(ServiceIterface.class,"methodA",hostname,port); Result = service.methodA(parameters);*/ // 向服务器发出请求建立连接 Socket socket = new Socket("localhost", 8899); // 从socket中获取输入输出流 InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter pw = new PrintWriter(outputStream); pw.println("hello"); pw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String result = br.readLine(); System.out.println(result); inputStream.close(); outputStream.close(); socket.close(); } }
package cn.itcast.bigdata.socket; public class GetDataServiceImpl { public String getData(String param){ return "ok-"+param; } }