Java Advanced Programming: Network

Posted by mad81 on Wed, 05 Jan 2022 13:10:44 +0100

1, Overview of network communication

1. Address of both parties:

  1. IP address: uniquely identifies the computer on the Internet
IP Address classification method 1: IPV4 and IPV6
	IPV4:4 Composed of 4 bytes, 4 zeros-255. Dot decimal identification
	IPV6:16 Bytes, written as 8 unsigned integers, each integer is represented by 4 hexadecimal white numbers, and colons are used between numbers
IP Address classification method 2: public network address(web)And private address(LAN)
  • java uses the class InetAddress to represent IP

  • Local loopback address (hostAddress)127.0.0.1; Host name: localhost

  • Domain name: www.baidu.com Com (domain name and IP address are mapped to each other and can be resolved to the corresponding IP address in DNS server)

  • How to instantiate InetAddress:
    InetAddress.getByName(String host) gets an instantiated object representing the ip address of the specified host
    InetAddress.getLocalHost() gets the instantiated object representing the real ip of the local machine

  • Two common methods of InetAddress:
    getHostName(): get host domain name
    getHostAddress(): get the address of the host

  1. Port number: distinguish different applications (processes) on a host
  • Different processes have different port numbers
  • The port number is specified as a 16 bit integer 0-65535
  • Port classification:
Recognized port: 0-1023,Is pre-defined as service communication occupancy.
	HTTP Occupied port number: 80; FTP Occupy port 21; Telnet Occupy port 23
 Registration port: 1024 - 49151: Assigned to a user process or application.
	(as Tomcat Occupied port number 8080, MySql Occupied port number 3306, Oracle Occupy port 1521, etc)
dynamic/Private port: 49152-65535
     Port number and IP The combination of addresses yields a network socket: Socket

2. Network communication protocol

  • OSI:
    OSI/RM protocol is formulated by ISO (International Organization for Standardization). It has three basic functions: providing developers with a necessary and general concept for development and improvement, and can be used to explain the framework connecting different systems

TCP/IP protocol:
Transmission control protocol / Internet Protocol refers to the protocol cluster that can realize information transmission between multiple different networks. TCP/IP protocol not only refers to TCP and IP, but also refers 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

  • Two important protocols of transport layer:
    • Transmission control protocol: TPC
    • User datagram protocol: UDP

3. Differences between TCP protocol and UDP protocol:

TCP protocol:

  • Before using TCP protocol, TPC connection must be established to form data transmission channel
  • Before transmission, three handshakes are used for point-to-point communication, which is reliable
  • There are two applications that communicate with TCP protocol: client and server
  • A large amount of data can be transmitted in the connection
  • After transmission, the established connection needs to be released, which is inefficient

UDP protocol:

  • Encapsulate data, source and destination into datagrams without establishing a connection
  • The size of each datagram is limited to 64k
  • No matter whether the other party is ready or not, the receiver does not confirm the receipt, so it is unreliable
  • Can broadcast and send
  • When sending data to borrow books, there is no need to release resources, low overhead and high speed

2, InetAddress class

  1. The object cannot be created directly because the constructor of InetAddress is declared private.
    1. Call getByName() to return an instantiated object with a specified IP address
    2. Call getLocalHost to represent the instantiated object of the native IP address
@Test
public void testInetAddress(){
    try {
        // This object corresponds to ip address 182.92.187.217
        // The constructor of this object is private and cannot create an object. You can only call the getByName method to return one
        InetAddress inetAddress = InetAddress.getByName("182.92.187.217");
        System.out.println(inetAddress);
        // When a domain name is filled in and output, the domain name is resolved
        InetAddress baidu = InetAddress.getByName("www.baidu.com");
        System.out.println(baidu);
       	// Get local host address 127.0.0.1
        InetAddress localhost = InetAddress.getByName("localhost"); 
        System.out.println(localhost);
        // InetAddress.getLocalHost(): method to obtain the real IP address of the local host:
        InetAddress localHost = InetAddress.getLocalHost(); 
        System.out.println(localHost);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
  1. Test the getHostName() method and getHostAddres() method
  • getHostName(): returns the hostName used when calling getByName(String hostName) to instantiate the InetAddress object, that is, the argument hostName
  • getHostAddress(): returns the IP address of the InetAddress object
    @Test
    public void testInetAddressMethod(){
        try {
            InetAddress baidu = InetAddress.getByName("www.baidu.com");
            System.out.println("baidu = " + baidu);
            System.out.println("baidu.getHostName() = " + baidu.getHostName());
            System.out.println("baidu.getHostAddress() = " + baidu.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
// result:
baidu = www.baidu.com/14.215.177.38
baidu.getHostName() = www.baidu.com // Use this as the host name when instantiating the InetAddress object
baidu.getHostAddress() = 14.215.177.38

3, Implement the program based on TCP protocol

In network programming, two programs on the network exchange data through a two-way communication connection. One end of the connection is called a socket.

1. Client

  • java uses Socket objects to represent clients
  • When creating a Socket object, you need to specify the IP address and port number of the server to facilitate sending data
  • Get the output stream by calling getOutputStream() to output data

2. Server side

  • ServiceSocket is used in java to represent the server side
  • When creating a ServiceSocket object, you need to indicate the IP address and program port number of the server to facilitate client access
  • Call accept() to get the Socket object representing the client, and call getInputStream() to get the input stream to receive the data passed by the client

3. Test procedure

be careful:

  • Start the server first
  • Close the connection before the program ends
  1. The client sends a string, and the server receives and prints it on the console
  • client
     @Test
    public void testClient() {
        Socket socket = null;
        BufferedOutputStream bos = null;
        try {
        	// Create a client object that indicates the ip address and port number of the server
            socket = new Socket("127.0.0.1", 20421);
           	// Gets the output stream used to output data
            OutputStream os = socket.getOutputStream();
            bos = new BufferedOutputStream(os);
            // Send a string to the server
            bos.write("it's all good, man".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • The server
    @Test
    public void testService() {
        ServerSocket serverSocket = null;
        Socket accept = null;
        BufferedInputStream bis = null;
        try {
        	// Instantiate ServerSocket to represent the server and indicate its own port number
            serverSocket = new ServerSocket(20421);
            // Call accept() to receive the socket from the client
            accept = serverSocket.accept();
            // Gets the input stream to receive data
            InputStream is = accept.getInputStream();
            bis = new BufferedInputStream(is);
            StringBuilder sb = new StringBuilder(255);
            byte[] buffer = new byte[255];
            int len ;
            while (-1 != (len = bis.read(buffer))) {
                sb.append(new String(buffer, 0, len));
            }
            // After receiving, print out the results
            System.out.println("This is the server, received from"+accept.getLocalAddress()+"Data:"+sb);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • result:
  1. The client sends the file to the server, which saves the file locally
  • client
    @Test
    public void cilent(){
        Socket socket = null;
        OutputStream os = null;
        BufferedInputStream br = null;
        try {
            // 1. Create a Socket object, and the constructor passes in an IP address object and port number
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress, 0627);
            // 2. Obtain the output stream through the socket object
            os = socket.getOutputStream();
            // To transfer a file, first read in the local file
            br = new BufferedInputStream(new FileInputStream("StreamFile\\Deadly poison master.jpg"));
            // 3. Read local files and transfer them
            byte[] buffer = new byte[20];
            int len ;
            while(-1 != (len = br.read(buffer))){
                os.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4. Close resources
            if( null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if( null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if( null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • The server
    @Test
    public void server(){
        Socket socket = null;
        InputStream inputStream = null;
        BufferedInputStream bos = null;
        FileOutputStream fos = null ;
        try {
            // 1. Create a ServerSocke object, and the constructor passes the service port number
            ServerSocket serverSocket = new ServerSocket(0627);
            // 2. Call ServerSocket The accept () method receives the client socket
            socket = serverSocket.accept();
            // 3. Obtain the input stream through socket
            inputStream = socket.getInputStream();
            bos = new BufferedInputStream(inputStream); // Wrap the input stream with a buffered stream
            fos = new FileOutputStream("StreamFile\\Deadly poison master_TCPTest.jpg"); // Get local file output stream
            // 4. Write data
            byte[] buffer = new byte[20];
            int len ;
            while( -1 != (len = bos.read(buffer))){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. Close resources
            if( null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if( null != bos ) {
                try {
                    bos.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();
                }
            }
        }
    }
  1. Send files from the client to the client, the server saves them locally, and returns "send successfully to the client"
The server sends data to the client:
Call received socket Object to output data
 The client receives the data sent by the server:
call socket Object to receive data
  • client
    @Test
    public void cilent() {
        Socket socket = null;
        OutputStream os = null;
        BufferedInputStream br = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            // 1. Create a Socket object, and the constructor passes in an IP address object and port number
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress, 0627);
            // 2. Obtain the output stream through the socket object
            os = socket.getOutputStream();
            // To transfer a file, first read in the local file
            br = new BufferedInputStream(new FileInputStream("StreamFile\\Deadly poison master.jpg"));
            // 3. Read local files and transfer them
            byte[] buffer = new byte[20];
            int len;
            while (-1 != (len = br.read(buffer))) {
                os.write(buffer, 0, len);
            }
            // The client adds an identifier to tell the server that the picture has been transmitted
            socket.shutdownOutput(); // Turn off data output
            // 4. Read the returned information and output it
            is = socket.getInputStream();
            bos = new ByteArrayOutputStream();
            while( -1 != (len = is.read(buffer)))
            {
                bos.write(buffer,0,len);
            }
            System.out.println(bos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. Close resources
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  • The server
    @Test
    public void server() {
        Socket socket = null;
        InputStream inputStream = null;
        BufferedInputStream bos = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            // 1. Create a ServerSocke object, and the constructor passes the service port number
            ServerSocket serverSocket = new ServerSocket(0627);
            // 2. Call ServerSocket The accept () method receives the client socket
            socket = serverSocket.accept();
            // 3. Obtain the input stream through socket
            inputStream = socket.getInputStream();
            bos = new BufferedInputStream(inputStream); // Wrap the input stream with a buffered stream
            fos = new FileOutputStream("StreamFile\\Deadly poison master_TCPTest3.jpg"); // Get local file output stream
            // 4. Write data
            byte[] buffer = new byte[20];
            int len;
            while (-1 != (len = bos.read(buffer))) {
                fos.write(buffer, 0, len);
            }
            // 5. Get the stream and send the return information
            os = socket.getOutputStream();
            os.write("Call client, call client, I am the server, I have received the data you sent".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 6. Close resources
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != bos) {
                try {
                    bos.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();
                }
            }
        }
    }
  • result

4, Implement the program based on UDP protocol

Classes datagram socket and datagram packet implement network program based on UDp protocol

  1. UPD datagrams are sent and received through datagram socket. The system does not guarantee that UDP packets can be safely delivered to the destination, nor can it determine when they can arrive
  2. The datagram packet object encapsulates UDP packets, which contain the IP address and port number of the sender and the IP address and port number of the receiver
  3. Each data packet in UDP protocol gives the completed address information, so there is no need to establish the connection between the sender and the receiver, just like sending express packages
  • In java, when implementing UDP protocol, both sender and receiver use datagram packet instance to encapsulate data and datagram socket to receive and send data
    @Test
    public void sender(){
        DatagramSocket socket = null;
        try {
        	// Create sender data socket object
            socket = new DatagramSocket();
            String str = "Paronychia really hurts";
            byte[] data = str.getBytes();
            InetAddress host = InetAddress.getLocalHost(); // Get the real IP address of this machine
            // Parameters: byte array for storing data, starting position and ending position of data, address of search room and port number
            DatagramPacket datagramPacket = new DatagramPacket(data,0,data.length,host,9090);// Encapsulate all the data in this class
			// Send packet
            socket.send(datagramPacket); // Sending and receiving are instances that use the DatagramPacket class
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null)
                socket.close();
        }
    }
  1. receiving end
    be careful:
  • When the program is started, the receiving end shall be started first, and the sending end shall be started
    // receiving end
    @Test
    public void receiver(){
        DatagramSocket socket = null;
        try {
        	// The receiver creates a data socket object
            socket = new DatagramSocket(9090 );
            byte[] buffer = new byte[100];
            InetAddress inet = InetAddress.getLocalHost(); // Get the IP address of this machine
            // Create packet object
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,inet,9090);
            socket.receive(packet);// Receive data, pass in the packet instance, and store the data in the packet
            System.out.println(new String(packet.getData(),0, packet.getLength()));// Output the data sent by the sender
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null)
                socket.close();
        }
    }
  1. result:

5, URL programming

  • URL: uniform resource locator, which indicates the address of a resource on the Internet
  • It is a specific URI, that is, the URL can be used to represent a resource. Second, it also indicates how to locat e the resource
  • Through URL, we can access various network resources on the internet
  • Basic structure of URL: Transport Protocol: / / host name: port number / file name # fragment name? parameter list

To access resources on the local server:

  • You need to install and configure Tomcat first, and start Tomcat after success,
    public void testURL(){
        URL url = null;
        InputStream is = null ;
        FileOutputStream fos = null ;
        HttpURLConnection urlConnection = null ;
        try {
        	// Create a URL for a resource on the local server
            url = new URL("http://localhost:8080//JavaInternetProgramming//beauty.jpg"); 
            // Get connection
            urlConnection = (HttpURLConnection) url.openConnection();
            // Connect
            urlConnection.connect();
            // Gets the input stream used to input the resources on the server into memory
            is = urlConnection.getInputStream();
            // Create an output stream to output resources from memory to local disk
            fos = new FileOutputStream("StreamFile\\beauty.jpg");// Get local file output stream
            byte[] buffer = new byte[10];
            int len;
            while (-1 != (len = is.read(buffer))) {
                fos.write(buffer, 0, len); // Output data to local disk
            }
            System.out.println("Get resources successfully, start closing connection");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // close resource
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (urlConnection != null)
                urlConnection.disconnect();
        }
        // Common methods for testing URL classes:
        System.out.println("url.getProtocol() = " + url.getProtocol()); // Obtain agreement
        System.out.println("url.getHost() = " + url.getHost()); // Get host
        System.out.println("url.getPort() = " + url.getPort()); // Get port
        System.out.println("url.getPath() = " + url.getPath()); // Get URL path
        System.out.println("url.getFile() = " + url.getFile()); // get files
        System.out.println("url.getQuery() = " + url.getQuery());
    }

Topics: Java