1,TCP通信的流程:

image.png

2,TCP的通信的程序组成及步骤:

A,服务端(先有输入): ServerSocket

  1. 1. 创建服务器端对象:
  1. ServerSocket serverSocket = new ServerSocket(8083);
  1. 2. 同意客户端请求:
  1. Socket socket = serverSocket.accept();
  1. 3. 创建输入流读取由客户端输入的数据:
  1. InputStream inputStream = socket.getInputStream();
  2. //新建一个空数据包接受数据:
  3. byte[] bytes = new byte[1024];
  4. //读取数据长度:
  5. int length = inputStream.read(bytes);
  6. System.out.println(new String(bytes,0,length));
  1. 4. 创建输出流向客户端输出数据:
  1. OutputStream outputStream = socket.getOutputStream();
  2. outputStream.write("da".getBytes());
  1. 5. 关闭:
  1. //关闭:
  2. outputStream.close();
  3. inputStream.close();
  4. socket.close();
  5. serverSocket.close();

B,客户端: Socket

  1. 6. 创建客户端对象:
  1. //服务器端ip和端口:
  2. Socket socket = new Socket("127.0.0.1", 8083);
  1. 7. 创建输出流向服务端输出数据:
  1. OutputStream outputStream = socket.getOutputStream();
  2. //getBytes:字符串转字节;
  3. outputStream.write("nnn".getBytes());
  1. 8. 创建输入流读取服务端输入的数据:
  1. InputStream inputStream = socket.getInputStream();
  2. //新建一个空数据包:(接收数据)
  3. byte[] bytes = new byte[1024];
  4. //获取数据长度;
  5. int len = inputStream.read(bytes);
  6. System.out.println(new String(bytes,0,len));
  1. 9. 关闭:
  1. outputStream.close();
  2. inputStream.close();
  3. socket.close();