Java core class library 8 -- network programming

Posted by php_gromnie on Mon, 17 Jan 2022 07:42:57 +0100

Java core class library 8 -- network programming

1. Seven layer network model

  • OSI (Open System Interconnect), namely open system interconnection, is a network interconnection model studied by ISO (International Organization for Standardization) in 1985.

  • When sending data, it is necessary to package the sent content layer by layer according to the above seven layer model and send it out.

  • When receiving data, it is necessary to unpack and display the received content layer by layer in the reverse order of the above seven layer model

2. Agreement

There must be some conventions or rules for computers to realize communication in the network. These conventions and rules are called communication protocol. Communication protocol can formulate unified standards for rate, transmission code, code structure, transmission control steps, error control, etc.

2.1. TCP (Transmission Control Protocol)

  • Connection oriented protocol
  • Establish connection = > communicate = > disconnect
  • The "three times handshake" mode is adopted before transmission
  • In the whole process of communication, the connection is maintained in the whole process to form a data transmission channel
  • It ensures the reliability and order of data transmission
  • It is a full duplex byte stream communication mode, which can transmit a large amount of data
  • After transmission, the established connection needs to be released, and the efficiency of sending data is relatively low

2.2. UDP (User Datagram Protocol)

  • Non connection oriented protocol
  • In the whole process of communication, there is no need to maintain a connection. In fact, there is no need to establish a connection
  • The reliability and order of data transmission are not guaranteed
  • It is a full duplex datagram communication mode, and the size of each datagram is limited to 64K
  • After sending data, there is no need to release resources, the overhead is small, the efficiency of sending data is relatively high and the speed is fast

3. IP and port

  • IP address is the only address identification in the Internet. In essence, it is an integer composed of 32-bit binary, called IPv4. Of course, there are 128 bit binary integers, called IPv6. At present, IPv4 is the mainstream
  • In essence, the port number is an integer composed of 16 bits binary. The representation range is 0 ~ 65535. The port number between 0 ~ 1024 is usually occupied by the system. It is recommended to start programming from 1025
  • IP address - you can locate a specific device
  • Port number - you can locate a specific process in the device
  • Network programming needs to provide: IP address + port number, which is called InetSocketAddress: Socket

4. TCP network programming

ServerSocket

Method declarationFunction introduction
public ServerSocket(int port)Constructs an object based on the port number specified by the parameter
public Socket accept()Listen and receive connection requests to this socket
public void close()Used to close the socket

Socket

Method declarationFunction introduction
public Socket(String host, int port)Constructs an object based on the specified host name and port
public InputStream getInputStream()The input stream used to get the current socket
public OutputStream getOutputStream()Gets the output stream of the current socket
public void close()Used to close the socket

4.1. The client sends it to the server

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream=null;
        try {
            serverSocket = new ServerSocket(8099);
            System.out.println("Waiting for client connection");
            socket = serverSocket.accept();
            System.out.println("Finally,I get you");
            //Thread.sleep(10000);
            inputStream = socket.getInputStream();
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=inputStream.read(buffer))!=-1){
                System.out.println(new String(buffer,0,len));
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream=null;
        try {
            socket = new Socket("127.0.0.1", 8099);
            outputStream = socket.getOutputStream();
            outputStream.write("hello, i am ruoye!".getBytes());
            outputStream.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4.2 server response

There is a problem with byte input / output stream. Read cannot read - 1. In this case, it should

outputStream.flush();
socket.shutdownOutput();

However, in multiple communications, it is obviously inappropriate to close the flow

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        try {
            serverSocket = new ServerSocket(8099);
            System.out.println("Waiting for client connection");
            socket = serverSocket.accept();
            System.out.println("Finally,I get you");
//            Thread.sleep(10000);
            inputStream = socket.getInputStream();
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=inputStream.read(buffer))!=-1){
                System.out.println(new String(buffer,0,len));
            }

            System.out.println("The server received a message");

            outputStream = socket.getOutputStream();
            outputStream.write("i know".getBytes());
            outputStream.flush();
            socket.shutdownOutput();
            System.out.println("Server send message");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream=null;
        InputStream inputStream=null;
        try {
            socket = new Socket("127.0.0.1", 8099);
            outputStream = socket.getOutputStream();
            outputStream.write("hello, i am ruoye!".getBytes());
            System.out.println("The client successfully sent the message");
            outputStream.flush();
            socket.shutdownOutput();
            inputStream = socket.getInputStream();
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=inputStream.read(buffer))!=-1){
                System.out.println(new String(buffer,0,len));
            }
            System.out.println("Client receives message");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4.3. DataInputStream stream

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        try {
            serverSocket = new ServerSocket(8099);
            System.out.println("Waiting for client connection");
            socket = serverSocket.accept();
            System.out.println("Finally,I get you");
//            Thread.sleep(10000);
            inputStream = socket.getInputStream();
            DataInputStream dataInputStream=new DataInputStream(inputStream);
            System.out.println(dataInputStream.readUTF());

            System.out.println("The server received a message");

            outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF("i know!");
            System.out.println("Server send message");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream=null;
        InputStream inputStream=null;
        try {
            socket = new Socket("127.0.0.1", 8099);
            outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF("i am ruoye!");
            System.out.println("The client successfully sent the message");
            System.out.println("================="+outputStream);
            outputStream.write("hello, i am ruoye!".getBytes());
            inputStream = socket.getInputStream();
            DataInputStream dataInputStream=new DataInputStream(inputStream);
            System.out.println(dataInputStream.readUTF());
            System.out.println("Client receives message");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4.4. Simple chat room

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        try {
            serverSocket = new ServerSocket(8099);
            System.out.println("Waiting for client connection");
            socket = serverSocket.accept();
            System.out.println("Finally,I get you");
            while (true) {
                inputStream = socket.getInputStream();
                DataInputStream dataInputStream=new DataInputStream(inputStream);
                String s = dataInputStream.readUTF();
                System.out.println(s);
                if ("bye".equalsIgnoreCase(s)){
                    break;
                }
                outputStream = socket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF("received"+s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream=null;
        InputStream inputStream=null;
        Scanner scanner=new Scanner(System.in);
        try {
            socket = new Socket("127.0.0.1", 8099);
            outputStream = socket.getOutputStream();
            while (true) {
                String next = scanner.next();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF(next);
                if ("bye".equalsIgnoreCase(next)){
                    break;
                }
                inputStream = socket.getInputStream();
                DataInputStream dataInputStream=new DataInputStream(inputStream);
                System.out.println(dataInputStream.readUTF());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4.5 multi person chat room

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8099);
            while (true){
                System.out.println("Waiting for client connection");
                Socket socket = serverSocket.accept();
                System.out.println("Finally,I get you");
                new Thread(new Conversation(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Conversation implements Runnable {
    private Socket socket;

    public Conversation(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream=null;
        OutputStream outputStream=null;

        try {
            while (true) {
                inputStream = socket.getInputStream();
                DataInputStream dataInputStream=new DataInputStream(inputStream);
                String s = dataInputStream.readUTF();
                System.out.println("received "+socket.getInetAddress()+" "+socket.getPort()+"News of:"+s);
                if ("bye".equalsIgnoreCase(s)){
                    break;
                }
                outputStream = socket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF("received "+socket.getInetAddress()+" "+socket.getPort()+":"+s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream=null;
        InputStream inputStream=null;
        Scanner scanner=new Scanner(System.in);
        try {
            socket = new Socket("127.0.0.1", 8099);
            outputStream = socket.getOutputStream();
            while (true) {
                String next = scanner.next();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF(next);
                if ("bye".equalsIgnoreCase(next)){
                    break;
                }
                inputStream = socket.getInputStream();
                DataInputStream dataInputStream=new DataInputStream(inputStream);
                System.out.println(dataInputStream.readUTF());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5. UDP network programming

DatagramSocket

Socket used to describe sending and receiving datagrams (sending or receiving point of parcel delivery service)

Method declarationFunction introduction
public DatagramSocket()Construct objects with no parameters
public DatagramSocket(int port)Constructs an object based on the port number specified by the parameter
public void receive(DatagramPacket p)Used to receive datagrams and store them in the location specified by the parameter
public void send(DatagramPacket p)Used to send the datagram specified by the parameter
public void close()Close the Socket and release related resources

DatagramPacket

To describe datagrams (used to implement connectionless package delivery service)

Method declarationFunction introduction
public DatagramPacket(byte[] buf, int length)Construct an object according to the array specified by the parameter, which is used to receive datagrams with length
public DatagramPacket(byte[] buf, int length, InetAddress address, int port)Construct the object according to the array specified by the parameter, and send the datagram to the specified address and port
public InetAddress getAddress()Used to obtain the communication address of the sender or receiver
public int getPort()Used to obtain the port number of the sender or receiver
public int getLength()Used to obtain the length of transmitted data or received data

InetAddress

Method declarationFunction introduction
public static InetAddress getLocalHost()Used to obtain the communication address of the current host
public static InetAddress getByName(String host)Obtain the communication address according to the host name specified by the parameter

5.1 simple broadcast

public class Receive {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8099);
            byte[] bytes=new byte[512];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);
            System.out.println("Waiting to send a message");
            datagramSocket.receive(datagramPacket);
            System.out.println("Waiting for content"+new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket!=null){
                datagramSocket.close();
            }
        }
    }
}
public class Send {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8100);
            String str="hello udp!";
            DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(), str.length(),new InetSocketAddress("127.0.0.1",8099));
            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket!=null){
                datagramSocket.close();
            }
        }
    }
}

5.1 broadcast with reply

public class Receive {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8099);
            byte[] bytes=new byte[512];
            DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);
            System.out.println("Waiting to send a message");
            datagramSocket.receive(datagramPacket);
            System.out.println("Waiting for content"+new String(bytes,0,datagramPacket.getLength()));

            String str = "i know";
            DatagramPacket datagramPacket1 = new DatagramPacket(str.getBytes(), str.length(),datagramPacket.getAddress(),datagramPacket.getPort());
            datagramSocket.send(datagramPacket1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket!=null){
                datagramSocket.close();
            }
        }
    }
}
public class Send {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8100);
            String str="hello udp!";
            DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(), str.length(),new InetSocketAddress("127.0.0.1",8099));
            datagramSocket.send(datagramPacket);

            byte[] bytes=new byte[512];
            DatagramPacket datagramPacket1 = new DatagramPacket(bytes,bytes.length);
            System.out.println("Waiting for reply message");
            datagramSocket.receive(datagramPacket1);
            System.out.println("Waiting for reply"+new String(bytes,0,datagramPacket1.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (datagramSocket!=null){
                datagramSocket.close();
            }
        }
    }
}

6,URL

Uniform resource locator

<transport protocol>://< host name >: < port number > / < resource address >
Method declarationFunction introduction
URL(String spec)Construct the object according to the string information specified by the parameter
String getProtocol()Get protocol name
String getHost()Get host name
int getPort()Get port number
String getPath()Get path information
String getFile()Get file name
URLConnection openConnection()Gets an instance of the URLConnection class

URLConnection

Method declarationFunction introduction
InputStream getInputStream()Get input stream
void disconnect()Disconnect
public class Test {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.baidu.com/");
            System.out.println(url.getProtocol());
            System.out.println(url.getHost());
            System.out.println(url.getPort());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

Topics: Java ReJava