Java network programming

Keywords: Java JavaSE

Java network programming

network model

  • OSI reference model
    The network is divided into seven layers: application layer, presentation layer, session layer, transport layer, network layer, data link layer and physical layer
  • TCP/IP reference model
    The network is divided into application layer, transport layer, Internet layer and host to network layer

Network communication elements

  • IP address InetAddress
    1. Identification of equipment in the network
    2. Hard to remember, available host name
    3. Local loopback address: 127.0.0.1 host name: localhost
  • Port number
    1. It is used to identify the logical address of the process and the identification of different processes
    2. Effective port: 065535, of which 01024 system uses or reserves port
  • transport protocol
    1. Rules of communication
    2. Common protocols: TCP,UDP
    UDP
    a. Encapsulate the data, source and destination into data packets without establishing a connection
    b. The size of each datagram is limited to 64k
    c. Because there is no connection, it is an unreliable protocol
    d. No need to establish a connection, fast
    TCP
    a. Establish a connection to form a data transmission channel
    b. Big data transmission in connection
    c. The connection is completed through three handshakes, which is a reliable protocol
    d. A connection must be established, which is slightly slower
    Three handshakes
    a. The first handshake establishes a connection. The client sends a syn packet to the server and enters SYN_SENT status, waiting for server confirmation
    b. In the second handshake, the server receives the SYN packet and must confirm the SYN of the client. At the same time, it also sends a SYN+ACK packet, and the server enters SYN_RECV status
    c. For the third handshake, the client receives the SYN+ACK packet from the server, like the server sending a confirmation packet ack. After this packet is sent, the client enters the ESTABLISHED(TCP connection succeeded) state and completes the three handshakes.

Socket

  • Socket is a mechanism provided for network services
  • There are sockets at both ends of the communication
  • Network communication is actually the communication between sockets
  • Data is transmitted between two sockets through IO
    UDP code display
// Sender
class SendMessageTask implements Runnable {
    @Override
    public void run() {
        try {
            DatagramSocket datagramSocket = new DatagramSocket(Demo.CLIENT_PORT);
            byte[] infos = "hello world".getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(infos, infos.length,
                    InetAddress.getByName(Demo.SERVER_HOST), Demo.SERVER_PORT);
            datagramSocket.send(datagramPacket);
            datagramSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// receiving end
class ReceiveMessageTask implements Runnable {
    @Override
    public void run() {
        try {
            DatagramSocket datagramSocket = new DatagramSocket(Demo.SERVER_PORT);
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            datagramSocket.receive(datagramPacket);
            // Get ip address and port
            InetAddress inetAddress = datagramPacket.getAddress();
            String ip = inetAddress.getHostAddress();
            int port = datagramPacket.getPort();
            byte[] contentBytes = datagramPacket.getData();
            int contentLength = datagramPacket.getLength();
            String content = new String(contentBytes, 0, contentLength);
            System.out.println(ip + ":" + port + " ---> " + content);
            datagramSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

TCP code display

// client
class ClientTask implements Runnable {
    @Override
    public void run() {
        try {
            Socket socket = new Socket(Demo.SERVER_HOST, Demo.SERVER_PORT);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello world".getBytes());
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);
            String content = new String(bytes, 0, length);
            System.out.println("The client receives feedback from the server ---> " + Demo.SERVER_HOST + ":" + Demo.SERVER_PORT + " ----> " + content);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// Server
class ServerTask implements Runnable {
    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(Demo.SERVER_PORT);
            Socket socket = serverSocket.accept();
            // Get address and port
            String hostname = socket.getInetAddress().getHostAddress();
            int port = socket.getPort();
            // Get content
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int length = inputStream.read(bytes);
            String content = new String(bytes, 0, length);
            System.out.println("The server receives a message from the client ---> " + hostname + ":" + port + " ----> " + content);
            // feedback information
            OutputStream outputStream = socket.getOutputStream();
            String responseContent = "hello java";
            outputStream.write(responseContent.getBytes());
            socket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Posted by mikemike on Sat, 25 Sep 2021 18:27:36 -0700