Java network programming

Posted by ozestretch on Sun, 30 Jan 2022 04:53:20 +0100

I mainly write this article to make a note for myself and make it easy for you to read.

preface

<font color=#999AAA

Tip: the following is the main content of this article. The following cases can be used for reference

1, TCP network programming

1. General

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, physical + data link layer)
3, Communication element 1: IP and port number

  1. IP: uniquely identifies the computer (communication entity) on the Internet

  2. Use the 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 www.mi. com www.sina. com www.jd. com www.vip. com

  5. Local loop address: 127.0.0.1 corresponds to: localhost

  6. How to instantiate InetAddress: two methods: getByName(String host) and getLocalHost()
    Two common methods: getHostName() / getHostAddress()

  7. Port number: the process running on the computer. Requirements: different processes have different port number ranges: it is specified as a 16 bit integer 0 ~ 65535.

  8. The combination of port number and IP address leads to a network Socket: Socket

public class InetAddressTest {

    public static void main(String[] args) {

        try {
            //File file = new File("hello.txt");
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");

            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);

            //Get local ip
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


    }


}

2. Realize TCP network programming

Example 1: the client sends information to the server, and the server displays the data on the console

public class TCPTest1 {

    //client
    @Test
    public void client()  {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1. Create a Socket object to indicate the ip and port number of the server
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2. Obtain an output stream for outputting data
            os = socket.getOutputStream();
            //3. Write data
            os.write("Hello, this is the client mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Closure of resources
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

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

            }
        }



    }
    //Server
    @Test
    public void server()  {

        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1. Create a ServerSocket on the server side and indicate its own port number
            ss = new ServerSocket(8899);
            //2. Call accept() to receive the socket from the client
            socket = ss.accept();
            //3. Get input stream
            is = socket.getInputStream();

            //It is not recommended to write like this. There may be garbled code
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            //4. Read the data in the input stream
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }

            System.out.println(baos.toString());

            System.out.println("Received from:" + socket.getInetAddress().getHostAddress() + "Data");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos != null){
                //5. Close resources
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }





    }

}

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

public class TCPTest2 {

    /*
    The exceptions involved here should be handled with try catch finally
     */
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.
        OutputStream os = socket.getOutputStream();
        //3.
        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //5.
        fis.close();
        os.close();
        socket.close();
    }

    /*
    The exceptions involved here should be handled with try catch finally
     */
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket ss = new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //6.
        fos.close();
        is.close();
        socket.close();
        ss.close();

    }
}

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

public class TCPTest3 {

    /*
        The exceptions involved here should be handled with try catch finally
         */
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.
        OutputStream os = socket.getOutputStream();
        //3.
        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //Turn off data output
        socket.shutdownOutput();

        //5. Receive data from the server and display it on the console
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) != -1){
            baos.write(buffer,0,len1);
        }

        System.out.println(baos.toString());

        //6.
        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    /*
    The exceptions involved here should be handled with try catch finally
     */
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket ss = new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

        System.out.println("Picture transfer complete");

        //6. The server gives feedback to the client
        OutputStream os = socket.getOutputStream();
        os.write("Hello, beauty, I have received the photo. It's very beautiful!".getBytes());

        //7.
        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();

    }
}

2, UDP network programming

public class UDPTest {

    //Sender
    @Test
    public void sender() throws IOException {

        DatagramSocket socket = new DatagramSocket();



        String str = "I am UDP Missile sent by";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);

        socket.close();

    }
    //receiving end
    @Test
    public void receiver() throws IOException {

        DatagramSocket socket = new DatagramSocket(9090);

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

        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        socket.close();
    }
}

3, URL network programming

1.URL: uniform resource locator, corresponding to a resource address on the Internet
2. Format: http://localhost:8080/examples/beauty.jpg?username=Tom Protocol host name port number resource address parameter list

public class URLTest {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            public String getProtocol() gets the protocol name of the URL
            System.out.println(url.getProtocol());
//            public String getHost() gets the host name of the URL
            System.out.println(url.getHost());
//            public String getPort() gets the port number of the URL
            System.out.println(url.getPort());
//            public String getPath() gets the file path of the URL
            System.out.println(url.getPath());
//            public String getFile() gets the file name of the URL
            System.out.println(url.getFile());
//            public String getQuery() gets the query name of the URL
            System.out.println(url.getQuery());




        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }


}

public class URLTest1 {

    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("day10\\beauty3.jpg");

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

            System.out.println("Download complete");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close resource
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }






    }
}

summary

I mainly write this article to make a note for myself and make it easy for you to read.

Topics: Java network