想要进行节点与节点间、客户端与服务器端、进程与进程间的通信,需要通过网络IO进行。JAVA通过Socket封装TCP/IP网络协议,进行网络之间的数据传输。
1.首先来回顾一下ISO七层模型和TCP/IP四层协议
2.了解一下JAVA通过Socket进行网络通信的流程
本地的进程通过PID标识唯一进程号,网络中通过协议+ip地址+端口号标识一个进程号,如:http://10.10.10.10:8080,网络间的进程被唯一标识后,可以进行网络通信。Socket将TCP/IP复杂的操作,封装为简单的接口供应用层使用,实现网络通信。就像文件IO的“打开—读写—关闭”一样,网络间的通信也变成客户端、服务器端可以给自己的”文件“写入内容,供对方读取,通信结束时关闭“文件”。
Socket通信流程:
服务端accept()方法会产生阻塞,等待客户端连接。
3.JAVA中的ServerSocket、Socket类
ServerSocket类: Socket类:
4.简单的传统BIO通信例子(同步阻塞一问一答式)
服务端代码
package service; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class BIOServerTest { public static void main(String[] args) throws IOException { new BIOServerTest().bind(); } public void bind() throws IOException { ServerSocket server = null; try { server = new ServerSocket(8000); Socket socket = null; while (true) { socket = server.accept(); new Thread(new BIOServerHandler(socket)).start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) { server.close(); } } } public class BIOServerHandler implements Runnable { private Socket socket; public BIOServerHandler(Socket socket) { this.socket = socket; } public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); out = new PrintWriter(this.socket.getOutputStream(), true); String body = null; while (true) { body = in.readLine(); if (body == null) { break; } System.out.println("client request " + body); out.println("ok"); } } catch (Exception e) { if (in != null) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (out != null) { out.close(); } if (socket!=null){ try { socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } } }