1. Socket Review and analysis I/0 Model

1.1 Socket summary :

Socket, A socket is the endpoint of a logical connection between two hosts .TCP/IP Protocol is transport layer protocol , It mainly solves how to transmit data in the network , and HTTP It's the application layer protocol , It mainly deals with how to package data .Socket Is the cornerstone of communication , It's supporting TCP/IP Basic operation unit of network communication of protocol . It is an abstract representation of the endpoint in the process of network communication , Contains five kinds of information necessary for network communication : The protocol used for the connection 、 localhost IP Address 、 Protocol port of local process 、 Remote host IP Address 、 The protocol port of the remote process .

1.2 Socket Overall process :

Socket Programming mainly involves two aspects: client and server , The first is to create a server socket on the server side (ServerSocket), And attach it to a port , The server listens for connections from this port . The range of port numbers is 0 To 65536, however 0 To 1024 Is the port number reserved for privileged Services , You can choose any port that is not currently used by other processes . When the client requests to connect to the server , According to the domain name of the server or IP Address , Add the port number , Open a socket . When the server accepts the connection , The communication between the server and the client operates like an input-output stream .

image.png


1.3 Code implementation

Server code :

package com.lagou.server;

import java.io.IOException;

import java.io.InputStream;

2. Client code

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ServerDemo {

  public static void main(String[] args) throws Exception {

    //1. Create a thread pool , If there is a client connection, create a thread , Communicate with

    ExecutorService executorService = Executors.newCachedThreadPool();

    //2. establish ServerSocket object

    ServerSocket serverSocket = new ServerSocket(9999);

    System.out.println(" The server has started ");

    while (true) {

      //3. Monitor client

      Socket socket = serverSocket.accept();

      System.out.println(" There is a client connection ");

      //4. Turn on new thread processing

      executorService.execute(new Runnable() {

        @Override

        public void run() {

          handle(socket);

       }

     });

   }

 }

  public static void handle(Socket socket) {

    try {

      System.out.println(" Threads ID:" + Thread.currentThread().getId()

          + "  Thread name :" + Thread.currentThread().getName());

      // Take the input stream from the connection to receive the message

      InputStream is = socket.getInputStream();

      byte[] b = new byte[1024];

      int read = is.read(b);

      System.out.println(" client :" + new String(b, 0, read));

      // Take out the output stream from the connection and call back

      OutputStream os = socket.getOutputStream();

      os.write(" Don't have the money ".getBytes());

   } catch (Exception e) {

      e.printStackTrace();

   } finally {

      try {

        // Close the connection

        socket.close();

     } catch (IOException e) {

        e.printStackTrace();

     }

   }

 }

}

Client code :

package com.lagou.client;

1.2 I/O Model

1.2.1 I/O Model description

1. I/O Simple understanding of the model : What kind of channel is used to send and receive data , To a large extent, it determines the process of program communication

performance

2. Java In support of 3 Network programming model /IO Pattern :BIO( Synchronize and block )、NIO( Synchronous nonblocking )、AIO( Asynchronous non-blocking )

Blocking and non blocking

It mainly refers to visiting IO Whether the thread of will block ( Or waiting )

Threads access resources , A way of handling whether the resource is ready

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.util.Scanner;

public class ClientDemo {

  public static void main(String[] args) throws Exception {

    while (true) {

      //1. establish Socket object

      Socket s = new Socket("127.0.0.1", 9999);

      //2. Take the output stream concurrent message from the connection

      OutputStream os = s.getOutputStream();

      System.out.println(" Please enter :");

      Scanner sc = new Scanner(System.in);

      String msg = sc.nextLine();

      os.write(msg.getBytes());

      //3. Take the input stream out of the connection and receive the call back

      InputStream is = s.getInputStream();

      byte[] b = new byte[1024];

      int read = is.read(b);

      System.out.println(" The boss said :" + new String(b, 0, read).trim());

      //4. close

      s.close();

   }

 }

}