network programming

7 minute read

Published:

Java basics – network programming

network programming

Introduction to Network Programming

Software structure

  • C/S structure: client/server structure
  • B/S structure: browser/server structure

Network communication protocol

  • Network communication protocol: The rules of connection and communication in a computer network are called network communication protocols
  • TCP/IP protocol: Transmission Interconnection Protocol/Internet Interconnection Protocol is the most basic and most extensive protocol

Protocol classification

  • UDP protocol: User Datagram Protocol is a connection-oriented protocol with low resource consumption and high communication efficiency. It is generally used for the transmission of audio, video and ordinary data, and cannot guarantee the integrity of data

    Features: data is limited to 64kb

  • TCP protocol: Transmission Control Protocol, a connection-oriented communication protocol, first establishes a logical connection and then sends data, providing reliable and error-free data transmission

    “Three handshake” is required to create a connection

    1. The client sends a connection request to the server and waits for the server to confirm
    2. The server responds to the client with a response, notifying the client that the request has been received
    3. The client sends a confirmation message to the server again to confirm the connection

    The three-way handshake can ensure the safety of data transmission, generally used for file upload, file download, web browsing, etc.

Three Elements of Network Programming

  1. Agreement

    Rules that must be observed in computer network communication

  2. IP address

    The Internet protocol address is the unique number of a computer in a network

    • IPv4: 32-bit binary number, usually divided into 4 bytes 0-255 decimal integer

    • IPv6: 128-bit binary numbers, usually divided into 8 groups of hexadecimal numbers

      Local ip address: 127.0.0.1, localhost

  3. Port number

    An integer represented by two bytes that can uniquely identify the process in the device, the range is 0-65535

    Port numbers before 1024 are used for well-known network services and applications

TCP communication program

Communication procedure

  1. The server program needs to be started in advance, waiting for the client to connect
  2. The client actively connects to the server, and the connection is successful to communicate

In Java, the client uses the java.net.Socket class and the server uses the java.net.ServerSocket class

note:

  1. Multiple clients interact with the server at the same time, the server must be clear which client to interact with
  2. If multiple clients interact with the server at the same time, they need to use multiple IO stream objects (get the Socket of the client and use the IO stream of the client to interact)

Socket class

java.net.Socket class implements client socket

  1. Construction method

    Socket(String host, int port): Create a stream socket and connect it to the specified port number on the specified host

  2. Member Method

    OutputStream getOutputStream(): Returns the output stream of this socket

    InputStream getInputStream(): Returns the input stream of this socket

    void close(): close this socket

  3. Implementation steps

    (1) Create a client object Socket, specify the ip address and port number of the server in the construction method

    (2) Use the getOutputStream method in the Socket object to obtain the network byte output stream object

    (3) Use the write method of the network byte output stream object to send data to the server

    (4) Use the method getInputStream in the Socket object to obtain the network byte input stream object

    (5) Use the read method of the network byte input stream object to read the data written by the server

    (6) Release resources (close)

  4. Note:

    (1) The client and server must use the network stream provided in the Socket to interact with each other, and cannot use the stream object created by themselves

    (2) When the client creates a Socket object, it will request the server

ServerSocket Class

java.net.ServerSocket class implements server socket

  1. Construction method

    ServerSocket(int port): Create a server socket bound to a specific port number

  2. Member Method

    Socket accept(): monitor and accept connections to this socket

  3. Implementation steps

    (1) Create a server object ServerSocket, specify the port number in the construction method

    (2) Use the accpet method in the ServerSocket object to obtain the requested client Socket object

    (3) Use the getInputStream method in the Socket object to obtain the network byte input stream object

    (4) Use the read method of the network byte input stream object to read the data sent by the client

    (5) Use the getOutputStream method in the Socket object to obtain the network byte output stream object

    (6) Use the write method of the network byte output stream object to write data back to the client

    (6) Release resources (close)

UDP communication program

Author: Dian stream of consciousness Link: https://www.jianshu.com/p/0a1f8fe54ee1 Source: Brief Book Copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

UDP protocol (User Datagram Protocol) is connectionless, unreliable, disorderly, and fast

When transmitting data, first define the data to be transmitted as a datagram, and the size is limited to 64k. In the datagram, specify the Socket (host address and port number) to which the data is requested, and then send the datagram.

DatagramPacket class: represents a datagram packet

DatagramSocket class: a class for end-to-end communication

  • Server-side implementation steps
    1. Create DatagramSocket, specify the port number
    2. Create DatagramPacket
    3. Accept the data information sent by the client
    4. Read the data
public class UDPServer {
    public static void main(String[] args) throws IOException {
        /*
         * Receive data sent by the client
         */
        //1. Create a server-side DatagramSocket, specify the port
        DatagramSocket socket=new DatagramSocket(8800);
        //2. Create a datagram to receive data sent by the client
        byte[] data =new byte[1024];//Create a byte array and specify the size of the received data packet
        DatagramPacket packet=new DatagramPacket(data, data.length);
        //3. Receive data sent by the client
        System.out.println("****The server has been started, waiting for the client to send data");
        socket.receive(packet);//This method will block until the datagram is received
        //4. Read data
        String info=new String(data, 0, packet.getLength());
        System.out.println("I am the server, the client says: "+info);

        /*
         * Response data to the client
         */
        //1. Define the client's address, port number, and data
        InetAddress address=packet.getAddress();
        int port=packet.getPort();
        byte[] data2="Welcome!".getBytes();
        //2. Create a datagram, including the response data information
        DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);
        //3. Responding to the client
        socket.send(packet2);
        //4. Close resources
        socket.close();
    }
}
  • Client implementation steps
    1. Define sending information
    2. Create a DatagramPacket that contains the information to be sent
    3. Create DatagramSocket
    4. Send data
public class UDPClient {
    public static void main(String[] args) throws IOException {
        /*
         * Send data to the server
         */
        //1. Define the address, port number, and data of the server
        InetAddress address=InetAddress.getByName("localhost");
        int port=8800;
        byte[] data="Username: jinbin; Password: 1997".getBytes();
        //2. Create a datagram, including the sent data information
        DatagramPacket packet=new DatagramPacket(data, data.length, address, port);
        //3. Create DatagramSocket object
        DatagramSocket socket=new DatagramSocket();
        //4. Send datagram to the server
        socket.send(packet);

        /*
         * Receive data from the server side response
         */
        //1. Create a datagram to receive data from the server-side response
        byte[] data2=new byte[1024];
        DatagramPacket packet2=new DatagramPacket(data2, data2.length);
        //2. Receive the data from the server
        socket.receive(packet2);
        //3. Read data
        String reply=new String(data2, 0, packet2.getLength());
        System.out.println("I am the client, the server said: "+reply);
        //4. Close resources
        socket.close();
    }
}