Network programming (preliminary understanding of TCP, UDP and URL)

Posted by PC Nerd on Thu, 17 Feb 2022 12:33:18 +0100

catalogue

1, There are two main problems in network programming:

2, Two elements in network programming:

3, Communication element 1: IP and port number

4, Realize TCP network programming

Example 1: the client sends information to the server, which displays the information on the console.

Example 2: the client sends a file to the server, which saves the file locally.

Example 3: send files from the client to the server, and the server saves them locally. And return the successful sending to the client. And close the corresponding connection.

5, Network programming of UDP protocol

6, URL: Uniform Resource Locator

 

1, There are two main problems in network programming:

1. How to accurately locate one or more hosts on the network; Locate a specific application on the host
 2. How to transmit data reliably and efficiently after finding the host

2, Two elements in network programming:

1. Corresponding question 1: IP and port number
 2. Corresponding question 2: provide network communication protocol: TCP/IP reference model (application layer, transmission layer, network layer, data link layer, physical layer)

3, Communication element 1: IP and port number

1.IP: uniquely identifies the computer (communication entity) on the Internet
 2. Use InetAddress class to represent IP in java
 3.Ip Classification: IPv4 and IPv6; World Wide Web and local area network
 4. Domain name: www.baidu.com com
 5. Local loop address: 127.0.0.1 corresponds to: localhost
 6. How to instantiate InetAddress: two methods: getbyname (string host), getlocalhost();
         Two common methods: getHostName() / getHostAddress()
7. Port number: the process running on the computer. Requirements: different processes have different port numbers
  Range: specified as a 16 bit integer 0 ~ 65535.
8. The combination of port number and IP address leads to a network Socket: Socket

4, Realize TCP network programming

Direct code display

Example 1: the client sends information to the server, which displays the information on the console.

public class TCPTest {
    //client
    @Test
    public void client() {
        Socket socket = null;
        OutputStream ops = null;
        try {
//1. Create a Socket object to indicate the ip and port number of the server
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 666);
//2. Get an output stream
            ops = socket.getOutputStream();
//3. Write out data with output stream
            ops.write("I'm a client".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//4. Resource shutdown: (stream and socket)
            if (ops != null) {
                try {
                    ops.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    //Server
    @Test
    public void server() {
        ServerSocket serverSocket = null;
        InputStreamReader isr = null;
        try {
//1. Create a ServerSocket on the server side and indicate its own port number
            serverSocket = new ServerSocket(666);
//2. The call to accept() indicates that the socket of the client can be received
            Socket accept = serverSocket.accept();
//3. Get an input stream
            //If there are Chinese characters, the bytes may be garbled So change the conversion flow
            isr = new InputStreamReader(accept.getInputStream());
//4. Read data from input stream
            char[] c = new char[100];
            int len;
            while ((len = isr.read(c)) != -1) {
                String s = new String(c, 0, len);
                System.out.println(s);
                //Other needs
                System.out.println("Received from client:" + serverSocket.getInetAddress().getHostName() + "Message from");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//5. Close resources (streams and socket s)
            if (isr != null) {

                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {

                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

Example 2: the client sends a file to the server, which saves the file locally.

public class TCPTest2 {
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"),622);
            os = socket.getOutputStream();
            fis = new FileInputStream(new File("lizhi.png"));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1){
                os.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void server(){
        ServerSocket ss = null;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        Socket accept = null;
        try {
            ss = new ServerSocket(622);
            accept = ss.accept();
            inputStream = accept.getInputStream();

            fos = new FileOutputStream(new File("Self-Improvement.png"));

            byte[] b = new byte[1024];
            int len ;
            while ((len = inputStream.read(b)) != -1){
                fos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (fos != null)
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
               accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss != null)
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }



    }
}

Example 3: send files from the client to the server, and the server saves them locally. And return the successful sending to the client. And close the corresponding connection.

public class TCPTest3 {
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 622);
            os = socket.getOutputStream();
            fis = new FileInputStream(new File("lizhi.png"));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                os.write(b, 0, len);
            }
//            Here, the client must manually stop the execution of read() because it is a blocking method and does not know when to stop.
            socket.shutdownOutput();

//            Here you need to receive messages from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            char[] chars = new char[5];
            int len1;
            while ((len1 = isr.read(chars)) != -1) {
                String s = new String(chars, 0, len1);
                System.out.print(s);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void server() {
        ServerSocket ss = null;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        Socket accept = null;
        try {
            ss = new ServerSocket(622);
            accept = ss.accept();
            inputStream = accept.getInputStream();

            fos = new FileOutputStream(new File("Self-Improvement.png"));

            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                fos.write(b, 0, len);
            }

//            Here you need to give feedback to the client
            OutputStream os = accept.getOutputStream();
            os.write("Your message was sent successfully".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss != null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}

5, Network programming of UDP protocol

public class UDPTest {
    //Sender
    @Test
    public void sender() {
        DatagramSocket Socket = null;
        try {
            Socket = new DatagramSocket();
            String s = new String("I am udp From");
            byte[] bytes = s.getBytes();
            InetAddress inet = InetAddress.getByName("127.0.0.1");

            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, inet, 666);

            Socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Socket.close();
        }


    }

    //receiving end
    @Test
    public void receiver()  {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(666);

            byte[] bytes = new byte[100];
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);

            datagramSocket.receive(packet);
            System.out.println(new String(packet.getData(), 0, packet.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            datagramSocket.close();
        }


    }
}

6, URL: Uniform Resource Locator

Five basic structures of URL
* http://localhost:8080/examples/beauty.jpg?username=Tom
 *Protocol host name port number resource address parameter list

Topics: network udp TCP/IP