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();//读服务器的流,阻塞,直到谁把流关了,就是把socket关了 System.out.println(result); inputStream.close(); outputStream.close(); socket.close(); } }
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是一直读,读到回车符才返回,所以客户端要发送火车福 BufferedReader br = new BufferedReader(new InputStreamReader(in)); // 从网络通信输入流中读取客户端发送过来的数据 // 注意:socketinputstream的读数据的方法都是阻塞的 ,没有消息也会一直读。 String line = ""; while ((line = br.readLine()) != null) {//加上while是一直读,不加while就只会读一次 line = br.readLine();//读客户端的流。直到socket的流关了 } /** * 将以下业务调用逻辑写成更加通用的:可以根据客户端发过来的调用类名、调用方法名、调用该参数来灵活调用 《反射》 */ GetDataServiceImpl getDataServiceImpl = new GetDataServiceImpl(); String result = getDataServiceImpl.getData(line); // 将调用结果写到sokect的输出流中,以发送给客户端 PrintWriter pw = new PrintWriter(out);//out是一个长连接, pw.println(result); pw.flush();//提交 } catch (IOException e) { e.printStackTrace(); } finally { try { if(null!=in) { in.close(); } if(null!=out) { out.close(); } if(null!=socket) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
package cn.itcast.bigdata.socket; public class GetDataServiceImpl { public String getData(String param){ return "ok-"+param; } }