Java network programming

1. Network Overview

The communication protocol usually consists of three parts: one is the syntax part, which is used to determine the type of dialogue between the two sides, the other is the syntax part, which is used to determine the mode of dialogue, and the third is the change rules, which determine the consent relationship between the two sides of the communication

2.IP address and port

IP address is the only communication entity in the identification network, which can be host, router, etc. in the network transmission based on IP protocol, all data packets must be identified by IP address. IP address is a 32-bit integer, usually 192.168.56.2

Port is a 16 bit integer used to indicate that data information is processed by the server of that program

3. There are four types of network functions provided by Java
1. InetAress is used to identify hardware resources on the network

The InetAress class represents IP addresses and has two subclasses: Inet4Address represents Ipv4 and inet6dress represents Ipv6. InetAdress has no constructor and provides the following two static methods to obtain instances:

    getByName(String host): get the corresponding InetAddress object according to the host.
    getByAddress(byte[] addr): obtain the corresponding InetAddress object according to the original IP address.

public class test {
    //  InetAddress class
    public static void main(String[] args) throws UnknownHostException {
        //Get native instance
        InetAddress address= InetAddress.getLocalHost();
        //Get computer name
        System.out.println("Local computer name:"+address.getHostName());
        //Get computer ip address
        System.out.println("IP Address:"+address.getHostAddress());
        byte[] bytes=address.getAddress();
        System.out.println("Byte array form:"+ Arrays.toString(bytes));
        System.out.println(address);
        //Obtain the interaddress instance according to the machine name or ip address
        InetAddress address1= InetAddress.getByName("LAPTOP-O9S9F7GC");
       // InetAddress address1= InetAddress.getByName("192.168.0.147");
        System.out.println("Local computer name:"+address1.getHostName());
        System.out.println("IP Address:"+address1.getHostAddress());
    }
}
//Operation results
 Local computer name: LAPTOP-O9S9F7GC
IP Address: 10.3.188.181
 Byte array form:[10, 3, -68, -75]
LAPTOP-O9S9F7GC/10.3.188.181
 Local computer name: LAPTOP-O9S9F7GC
IP Address: 10.3.188.181

2. URL uniform resource locator can directly read or write data on the network through the URL

The URL class is defined in the java.net package, which is used to process the content about the URL. The creation and use of URL classes are described below.
java.net.URL provides rich URL construction methods, and resources can be obtained through java.net.URL.

3. Sockets uses the TCP protocol to implement the socket related classes of network communication

TCP, the full English name of Transmission control protocol, translates directly into: Transmission control protocol. It is a connection oriented, reliable and byte stream based transport layer communication protocol. It is a transmission protocol specially designed to provide reliable end-to-end byte stream on the unreliable Internet. TCP/IP protocol refers not only to TCP and IP, but also to a protocol cluster composed of FTP, SMTP, TCP, UDP, IP and other protocols. It is called TCP/IP protocol because TCP protocol and IP protocol are the most representative in TCP/IP protocol.

  Create the server and start the thread

public class Server {
    public static void main(String[] args) throws IOException {
        Socket socket=null;
          int count=0;
         //1. Create a server-side Socket and specify the bound port
        ServerSocket serverSocket=new ServerSocket(8888);
        System.out.println("The server is about to start, waiting for the customer service terminal to connect");
        while (true){
             socket =serverSocket.accept();//Call the accept () method to listen and wait for the customer service side to connect
            SeverThread severThread=new SeverThread(socket);//Create thread
            severThread.start();//Start thread
            count++;
            System.out.println("Number of customer service terminals"+count);
            InetAddress address=socket.getInetAddress();
            System.out.println("Customer service IP Address:"+address);
            System.out.println("Local computer name:"+address.getHostName());
        }
    }
}
//Start the server
 Output results
 The server is about to start, waiting for the customer service terminal to connect
//After starting the customer service terminal
 Output results
 The server is about to start, waiting for the customer service terminal to connect
 Number of customer service terminals 1
 Customer service IP Address:/10.3.188.181
 Local computer name: LAPTOP-O9S9F7GC
 I am the server, and the customer service side says: user name: TOM;Password: 1234561
//Server thread processing class
public class SeverThread extends Thread{
    Socket socket=null;
    InputStream is=null;
    public SeverThread(Socket socket){
        this.socket=socket;
    }
    //The operation performed by the thread,
    public void run(){
        //3. Obtain the input stream and read the customer service information
        try {//Byte output stream
            is = socket.getInputStream();
            InputStreamReader isr=new InputStreamReader(is);//Convert byte stream to character stream
            BufferedReader br=new BufferedReader(isr);//Add input stream to buffer
            String info=null;
            while ((info=br.readLine())!=null)
            {
                System.out.println("I'm the server, and the customer service side says:"+info);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4. Obtain the output stream to respond to the customer service request
        try (OutputStream os = socket.getOutputStream()) {
            PrintWriter pw = new PrintWriter(os);//Wrap the output stream as a print stream
            pw.write("Hello ua");//
            pw.flush(); //Send information to the server
        }//Byte output stream
        catch (IOException e) {
            e.printStackTrace();
      } }}

  Create customer service end

    public static void main(String[] args) throws IOException {
        //1. Create a customer service Socket and specify the server address port
        Socket socket=new Socket("LAPTOP-O9S9F7GC",8888);
        //2. Obtain the output stream and send information to the server
         OutputStream os=socket.getOutputStream();//Byte output stream
        PrintWriter pw=new PrintWriter(os);//Wrap the output stream as a print stream
        pw.write("user name: TOM;Password: 123456");//
        pw.flush(); //Send information to the server
        //Close output stream
        socket.shutdownOutput();
        //3. Obtain the input stream and read the information of the server
        InputStream is=socket.getInputStream();//Byte output stream
        InputStreamReader isr=new InputStreamReader(is);//Convert byte stream to character stream
        BufferedReader br=new BufferedReader(isr);//Add input stream to buffer
        String info=null;
        while ((info=br.readLine())!=null)
        {
            System.out.println("At the customer service end, the server said:"+info);
        }
        pw.close();
        br.close();
        is.close();
        os.close();
        socket.close();
    }
//After starting the customer service terminal, start the service terminal
 Output results
 At the customer service end, the server said: Hello ua

4. Datagram uses UDP protocol to save data in datagram and communicate through network

UDP is the abbreviation of user datagram protocol, a connectionless protocol. A packet that provides data to be sent between applications. UDP is used to support network applications that need to transfer data between computers. Many client / server mode network applications, including network video conference system, need to use UDP protocol. UDP protocol has been used for many years since it came out. Although its initial glory has been covered by some similar protocols, UDP is still a very practical and feasible network transport layer protocol even today.

udp creates a customer service side and a service side

 public static void main(String[] args) throws IOException {
        //1 create the specified port on the server side
        DatagramSocket socket=new DatagramSocket(8800);
        //2. Create a datagram to receive the data sent by the customer service terminal
        byte[]date=new byte[1024];//Create a byte array to specify the size of the received packet
        DatagramPacket packet=new DatagramPacket(date, date.length);
        //3. Receive the data sent by the customer service terminal
        System.out.println("Start the server and wait for the customer service terminal to send messages");
        socket.receive(packet);//This method blocks until it receives a datagram
        //4 read data
        String info=new String(date,0, packet.getLength());
        System.out.println("I'm the server, and the customer service side says:"+info);
        /*
         Respond to customer service data
         */
        //1. Define the customer service end address, port and data
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        byte[] date2 = "Welcome".getBytes();
        //Create datagram
        DatagramPacket packet2=new DatagramPacket(date2, date2.length,address,port);
        //Send datagram
        socket.send(packet2);
        //close resource
        socket.close();
    }
//Start the server
 Start the server and wait for the customer service terminal to send messages
//After starting the customer service terminal
 I am the server, and the customer service side says: user name: admin;Password 123

 

    public static void main(String[] args) throws IOException {
        //1 determine the address, port number and data of a server
        InetAddress address = InetAddress.getByName("LAPTOP-O9S9F7GC");
        int port = 8800;
        byte[] date = "user name: admin;Password 123".getBytes();
        //2. Create datagram, including the sent data information
        DatagramPacket packet=new DatagramPacket(date, date.length,address,port);
        //3. Create DatagramSocket object
        DatagramSocket socket=new DatagramSocket();
        //4 send datagram to server
        socket.send(packet);
        //Receive server response
        byte[]date2=new byte[1024];//Create a byte array to specify the size of the received packet
        DatagramPacket packet2=new DatagramPacket(date2, date2.length);
        //3. Receive the data sent by the customer service terminal
        socket.receive(packet2);//This method blocks until it receives a datagram
        //4 read data
        String info1=new String(date2,0, packet2.getLength());
        System.out.println("I'm the customer service side, and the server says:"+info1);
    }
//Start result
 I am the customer service side, and the server says: Welcome

4. Difference between UPD and tcp

  • TCP is based on connection, and UDP is connectionless;
  • There are more TCP and less UDP requirements for system resources;
  • UDP program structure is simple;
  • TCP is stream mode, while UDP is datagram mode;
  • TCP ensures data correctness, while UDP may lose packets; TCP guarantees the data order, but UDP does not;

Keywords: Java

Added by melbell on Tue, 23 Nov 2021 01:36:03 +0200