java network learning notes

Posted by satanclaus on Wed, 05 Jan 2022 22:59:28 +0100

1: InetAddress class

1. What is InetAddress

This class represents an Internet Protocol (IP) address.

2. Common usage:

            InetAddress inetAddress = InetAddress.getByName("www.jd.com");//Create an InetAddress object through the domain name
            InetAddress inetAddress1 = InetAddress.getLocalHost();//Create a native InetAddress object
            InetAddress inetAddress2= InetAddress.getByName("127.0.0.1");//Creating InetAdress objects over IP
            System.out.println(inetAddress);//Get the string of domain name + IP -- www.jd com/180.97.189.3
            System.out.println("ip:"+inetAddress.getHostAddress());//ip
            System.out.println("domain name:"+inetAddress.getHostName());//Domain name / / or the name of your computer
            System.out.println(inetAddress1);

3. Supplementary notes

Native IP: 127.0.0.1
IPv4:
IPv4. The IP address of is composed of 32-bit binary numbers. For ease of use, it is often represented by XXX XXX. XXX. In the form of XXX, each group of XXX represents a decimal number less than or equal to 255. This representation method is called dotted decimal. For example, an IP address of Wikimedia is 208.80.152.2. Addresses can be divided into five categories: A, B, C, D and E, of which class E belongs to special reserved addresses.
IPv6:
The IPv6 address is 128 bits long and consists of eight 16 bit fields, with adjacent fields separated by colons. Each field in an IPv6 address must contain a hexadecimal number, while an IPv4 address is represented in dotted decimal notation

2: Socket

1. What is a Socket

Socket: socket
This class implements client sockets (also known as sockets). A socket is the endpoint of communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class. Applications can configure themselves to create sockets suitable for local firewalls by changing the socket factory implemented by creating sockets.

2. Common socket methods

Socket socket = new Socket(InetAddress serverIp,String port);
//Create a connected Socket class object through the InetAddress object and port number
 socket.getInputStream();//Get the input stream and return the InputStrea m object
 socket.getOutputStream();//Get the output stream and return the OutputStream object
 socket.close();//Close connection
 ServerSocket serverSocket = new ServerSocket(String port);//Create an accepted ServerSocket class object through the port number
 serverSocket.accept();//Wait for the user to connect and return a Socket object to receive the information transmitted by the user
 serverSocket.close();//Close connection

3.Socket application case

TCP function implementation

4. Datagram socket and datagram packet classes

1. Introduction to datagram socket

This class represents the socket used to send and receive datagram packets.

The datagram socket is the sending or receiving point of the packet transfer service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another can be routed differently and can arrive in any order.

Example: DatagramSocket s = new DatagramSocket(null); s.bind(new InetSocketAddress(8888)); Where, it is equivalent to: datagram socket s = new datagram socket (8888); In both cases, a datagram socket will be created to receive broadcasts on UDP port 8888.

2. Introduction to datagram packet

This class represents a datagram packet.
Datagram packets are used to implement connectionless packet transmission services. Each message is routed from one machine to another based only on the information contained in the packet. Multiple packets sent from one machine to another may have different routes and may arrive in any order. Packet transfer is not guaranteed

3. Steps for using UDP

Sender:

		//1. Establish connection
        DatagramSocket socket = null;
        //2. Get the connection object
        //Get the IP and port number of the other party to connect
        InetAddress Ip = null;
        int port = 9999;
        //4. Create data package
        String msg = "Hello";
        DatagramPacket packet = null;
        try {
            socket = new DatagramSocket();
            Ip = InetAddress.getByName("localhost");
            //Data, the beginning of the length of the data, the address to send
            packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,Ip,port);
            //5. Send packet
            socket.send(packet);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6. Close resources
            if (socket != null){
                socket.close();
            }
        }

Receiving end:

        DatagramSocket socket = null;
        try {
            //1. Open your own port (the port connected by the client)
            socket = new DatagramSocket(9999);
            //2. Receive data
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            socket.receive(packet);//Blocking reception
            //3. Data processing
            byte[] target = packet.getData();
            int len=0;
            if (target.length!=0){
                for (int i=0;i<target.length;i++){
                    if (target[i]=='\0'){
                        len=i;
                        break;
                    }
                }

            }
            //4. Output data
            System.out.println("from:"+packet.getAddress());
            System.out.println(new String(target,0,len));

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (socket!=null){
                socket.close();
            }
        }

4.UDP implementation of online chat case

UDP implementation of online chat case

3, URL

The content is relatively simple, directly on the example code

package URL;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;

public class URLTest {
    public static void main(String[] args) {
        HttpURLConnection connection = null;
        InputStream in = null;
        FileOutputStream fos = null;
        try {
            //Get the HTML page of Baidu. / / you can also get the audio and video corresponding to the URL
            URL url = new URL("https://www.baidu.com/");
            //Open connection via URL
            connection = (HttpURLConnection) url.openConnection();
            //Gets the input stream of the connection
            in = connection.getInputStream();
            //Save file
            fos = new FileOutputStream("1.html");//The file suffix corresponds to the acquired file
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = in.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
            //Gets the status of the connection
            String msg = connection.getResponseMessage();
            System.out.println("Connection status:"+msg);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //close resource
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in !=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                connection.disconnect();
            }
        }
    }
}

Topics: Java network socket