[Shangsi Valley _java foundation] XV. Network programming

Posted by gunhoe86 on Sun, 23 Jan 2022 05:37:08 +0100

reference material

  1. https://blog.csdn.net/PorkBird/article/details/113727633
  2. https://www.bilibili.com/video/BV1Kb411W75N?p=636&spm_id_from=pageDriver

1. Overview of network programming

  • Java is a language on the Internet. It provides support for network applications at the language level. Programmers can easily develop common network applications.

  • The network class library provided by java can realize painless network connection. The underlying details of networking are hidden in the Java Native installation system and controlled by the JVM. And Java implements a cross platform network library. Programmers face a unified network programming environment.

  • Computer network:

    The computers distributed in different geographical regions and special external equipment are interconnected with communication lines to form a large-scale and powerful network system, so that many computers can easily transfer information to each other and share hardware, software, data information and other resources.

  • Purpose of network programming:

    Data exchange and communication with other computers directly or indirectly through network protocol.

  • There are two main problems in network programming:

    • How to accurately locate one or more hosts on the network; Locate a specific application on the host
    • How to transfer data reliably and efficiently after finding the host

2. Overview of network communication elements

2.1 how to realize mutual communication between hosts in the network

  • Address of both parties

    • IP
    • Port number
  • Certain rules (i.e. network communication protocol. There are two sets of reference models)

    • OSI reference model: the model is too idealized to be widely popularized on the Internet
    • TCP/IP reference model (or TCP/IP Protocol): a de facto international standard.
  • Network communication protocol

  • 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

  • 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, transport layer, network layer, physical + data link layer)

3. Communication element 1: IP and port number

3.1 IP address: InetAddress

  • Uniquely identifies the computer (communication entity) on the Internet

  • Local loopback address: 127.0.0.1 hostname: localhost

  • IP address classification method 1: IPV4 and IPV6

    • IPV4: 4 bytes, 4 0-255. About 4.2 billion and 3 billion are in North America and 400 million in Asia. It was exhausted in early 2011. Expressed in dotted decimal system, such as 192.168.0.1
    • IPV6: 128 bits (16 bytes), written as 8 unsigned integers. Each integer is represented by four hexadecimal bits, separated by colons (:), such as 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
  • IP address classification method 2: public network address (used by the World Wide Web) and private address (used by the local area network). 192.168. The private address at the beginning is 192.168.0.0 – 192.168.255.255, which is specially used within the organization

  • Features: not easy to remember

3.2 port number

  • The port number identifies the process (program) running on the computer
    • Different processes have different port numbers
    • It is specified as a 16 bit integer 0 ~ 65535.
    • Port classification:
      • Recognized port: 0 ~ 1023. Occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
      • Registration port: 1024 ~ 49151. Assigned to a user process or application. (for example, Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.).
      • Dynamic / private ports: 49152 ~ 65535.
  • The combination of port number and IP address yields a network Socket: Socket.

3.3 InetAddress class

  • The InetAddress class mainly represents the IP address. There are two subclasses: Inet4Address and Inet6Address.

  • The InetAddress class object contains the domain name and IP address of an Internet host address: www.atguigu.com COM and 202.108.35.210.

  • The domain name is easy to remember. When a host's domain name is entered when connecting to the network, the domain name server (DNS) is responsible for converting the domain name into an IP address, so as to establish a connection with the host------- Domain name resolution

  • The InetAddress class does not provide a public constructor, but provides the following static methods to obtain
    InetAddress instance
    public static InetAddress getLocalHost() gets the local IP address
    public static InetAddress getByName(String host)

  • InetAddress provides the following common methods
    public String getHostAddress(): returns the IP address string (expressed in text).
    public String getHostName(): get the host name of this IP address
    public boolean isReachable(int timeout): test whether the address can be reached

package pers.chh3213.InetAdressClass;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : chh3213
 * @version : 1.0
 * @Project : network_program
 * @Package : pers.chh3213.InetAdressClass
 * @ClassName : InetAddressTest.java
 * @createTime : 2022/1/22 9:40
 * @Email :
 * @Description :
 */
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 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 transfer 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, transport 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.
 * Requirement: different processes have different port numbers
 * Range: specified as a 16 bit integer 0 ~ 65535.
 *
 * 8. The combination of port number and IP address yields 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();
        }
    }
}

4. Communication element 2: network protocol

  • Network communication protocol

    There must be some conventions to realize communication in computer network, that is, communication protocol, and formulate standards for rate, transmission code, code structure, transmission control steps, error control, etc.

  • Problem: the network protocol is too complex

    Computer network communication involves many contents, such as specifying source address and target address, encryption and decryption, compression and decompression, error control, flow control and routing control. How to realize such a complex network protocol?

  • The idea of communication protocol layering
    When making an agreement, break down the complex components into some simple components, and then combine them. The most commonly used composite method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the next layer, and there is no relationship with the next layer. Each layer does not affect each other, which is conducive to the development and expansion of the system.

4.1 TCP/IP protocol cluster

  • There are two very important protocols in the transport layer protocol:

    • Transmission control protocol (TCP)
    • User datagram protocol (UDP).
  • TCP/IP is named after its two main protocols: * * transmission control protocol (TCP) and network interconnection protocol (IP) * *. It is actually a group of protocols, including multiple protocols with different functions and related to each other.

  • IP(Internet Protocol) protocol is the main protocol of network layer, which supports data communication between networks.

  • From a more practical point of view, TCP/IP protocol model forms an efficient four layer architecture, namely physical link layer, IP layer, transport layer and application layer.

  • TCP protocol:
    -Before using TCP protocol, a TCP connection must be established to form a data transmission channel
    -Before transmission, the "triple handshake" mode is adopted for point-to-point communication, which is reliable
    -Two application processes communicating 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 the data, source and destination into packets without establishing a connection
    • The size of each datagram is limited to 64K
    • Whether the sending party is ready or not, the receiving party does not confirm the receipt, so it is unreliable
    • Can broadcast and send
    • At the end of sending data, there is no need to release resources, low overhead and high speed


4.2 Socket

  • Using socket to develop network applications has long been widely used, so that it has become a reality
    Standards on.
  • Only when the IP address and port number with unique identification on the network are combined together can they form a unique identifier
    Identifier socket.
  • Socket s should be provided at both ends of the communication, which is the end point of communication between two machines.
  • Socket s should be provided at both ends of the communication, which is the end point of communication between two machines.
  • Socket allows the program to treat the network connection as a stream, and the data is transmitted between the two sockets through IO.
  • Generally, the application that initiates communication actively belongs to the client, and the one waiting for communication request is the server.
  • Socket classification:
    • stream socket: use TCP to provide reliable byte stream services
    • datagram socket: provide "best effort" datagram service using UDP

5. TCP network programming

Socket based programming in Java language is divided into server-side programming and client-side programming. Its communication model is shown in the figure:

  • The working process of the client Socket includes the following four basic steps:

    • Create Socket: construct a Socket class object according to the IP address or port number of the specified server. If the server responds, a communication line from the client to the server is established. If the connection fails, an exception will appear.
    • Open the input / output stream connected to the Socket: use getInputStream() method to obtain the input stream and getOutputStream() method to obtain the output stream for data transmission
    • Read / write the Socket according to a certain protocol: read the information put into the line by the server through the input stream (but cannot read the information put into the line by itself), and write the information into the thread through the output stream.
    • Close Socket: disconnect the client from the server and release the line
  • The working process of the server program includes the following four basic steps:

    • Call ServerSocket(int port): create a server-side socket and bind it to the specified port. Used to listen for client requests.
    • Call accept(): listen for connection requests. If the client requests a connection, it accepts the connection and returns the communication socket object.
    • Call getOutputStream() and getInputStream () of the Socket class object: get the output stream and input stream, and start sending and receiving network data.
    • Close ServerSocket and Socket object: the client access ends and the communication Socket is closed.

5.1 creating Socket objects by the client

  • The client program can use the Socket class to create objects, which will automatically initiate a connection to the server at the same time. The constructor of the Socket is:
    • Socket(String host,int port)throws UnknownHostException,IOException: initiate a TCP connection to the server (the domain name is host and the port number is port). If it succeeds, create a socket object, otherwise throw an exception.
    • Socket(InetAddress address,int port)throws IOException: initiates a connection according to the IP address and port number represented by the InetAddress object.
  • The process that the client establishes the socketAtClient object is to send a socket connection request to the server
    Socket s = new
    Socket("192.168.40.165" ,9999);
    OutputStream out = s.getOutputStream();
    out.write(" hello".getBytes());
    s.close();
    

5.2 creating a ServerSocket object by the server

  • The ServerSocket object is responsible for waiting for the client to request to establish a socket connection, similar to the salesman in a window of the post office. In other words, the server must establish a ServerSocket object waiting for the client's request to establish a socket connection in advance.

  • The so-called "receiving" the client's Socket request means that the accept() method will return a Socket object

    ServerSocket ss = new ServerSocket(9999);
    Socket s = ss.accept ();
    InputStream in = s.getInputStream();
    byte[] buf = new byte[1024];
    int num = in.read(buf);
    String str = new String(buf,0,num);
    System.out.println(s.getInetAddress().toString()+" :" +str);
    s.close();
    ss.close();
    

5.3 examples

  • The client sends the content to the server, and the server prints the content to the console. (start the server first)

    • Client steps
      1. Create a Socket object to indicate the ip and port number of the server
      2. Obtain an output stream for outputting data
      3. Write data
      4. Closure of resources
    • Server steps
      1. Create a ServerSocket on the server side and indicate its own port number
      2. Call accept() to receive the socket from the client
      3. Get input stream
      4. Read the data in the input stream
      5. Close resources
    package pers.chh3213.socket;
    
    import org.junit.Test;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TCPTest {
    
        //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("127.0.0.1");
                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".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 in this way. There may be garbled codes (one symbol in Chinese accounts for two characters)
    //        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();
                    }
                }
            }
        }
    }
    
    
  • The client sends the file to the server, which saves the file locally.

    package pers.chh3213.socket;
    
    import org.junit.Test;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * Network programming for TCP
     * Example 2: the client sends a file to the server, and the server saves the file locally.
     *
     * @author subei
     * @create 2020-05-16 17:05
     */
    public class TCPTest2 {
    
        /**
         * The exceptions involved here should be handled with try catch finally
         * @throws IOException
         */
        @Test
        public void test() throws IOException {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),8090);
            OutputStream os = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(new File("164.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1){
                os.write(buffer,0,len);
            }
            fis.close();
            os.close();
            socket.close();
        }
    
        /**
         * The exceptions involved here should be handled with try catch finally
         * @throws IOException
         */
        @Test
        public void test2() throws IOException {
            ServerSocket ss = new ServerSocket(8090);
            Socket socket = ss.accept();
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File("1.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
            fos.close();
            is.close();
            socket.close();
            ss.close();
        }
    }
    
    
    
  • Send files from the client to the server, and the server saves them locally. And return "send successfully" to
    client. And close the corresponding connection.

    import org.junit.Test;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * Realize network programming of TCP
     * 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
         * @throws IOException
         */
        @Test
        public void test() throws IOException {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
            OutputStream os = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(new File("10.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1){
                os.write(buffer,0,len);
            }
            //Turn off the output of data - if not, it will be blocked
            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());
    
            fis.close();
            os.close();
            socket.close();
            baos.close();
        }
    
        /**
         * The exceptions involved here should be handled with try catch finally
         * @throws IOException
         */
        @Test
        public void test2() throws IOException {
            ServerSocket ss = new ServerSocket(9090);
            Socket socket = ss.accept();
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File("11.jpg"));
            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, the photo has been received!".getBytes());
    
            fos.close();
            is.close();
            socket.close();
            ss.close();
            os.close();
        }
    }
    
    

5.4 practice

  • The server reads the picture and sends it to the client, and the client saves the picture locally
  • The client sends text to the server, and the server will convert the text into uppercase and return it to the client.

6. UDP network programming

  • Classes datagram socket and datagram packet implement network programs based on UDP protocol.

  • UDP datagrams are sent and received through datagram socket. The system does not guarantee that UDP datagrams can be safely sent to the destination, nor can it determine when they can arrive.

  • The datagram packet object encapsulates UDP datagrams, which contain the IP address and port number of the sender and the IP address and port number of the receiver.

  • Each datagram in UDP protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver. It's like sending an express package.

  • technological process:

    • Datagram socket and datagram packet
    • Establish sender and receiver
    • Create packet
    • Call Socket sending and receiving methods
    • Close Socket
  • The sender and receiver are two independent running programs

    • Sender
      DatagramSocket ds = null;
      try {
      	ds = new DatagramSocket();
      	byte[] by = "hello,atguigu.com".getBytes();
      	DatagramPacket dp = new DatagramPacket(by, 0, by.length,
      	InetAddress.getByName("127.0.0.1"), 10000);
      	ds.send(dp);
      	} catch (Exception e) {
      		e.printStackTrace();
      	} finally {
      		if (ds != null)
      			ds.close();
      }
      
    • receiving end
      At the receiving end, specify the listening port.
      DatagramSocket ds = null;
      try {
      ds = new DatagramSocket(10000);
      byte[] by = new byte[1024];
      DatagramPacket dp = new DatagramPacket(by, by.length);
      ds.receive(dp);
      String str = new String(dp.getData(), 0, dp.getLength());
      System.out.println(str + "--" + dp.getAddress());
      } catch (Exception e) {
      e.printStackTrace();
      } finally {
      if (ds != null)
      ds.close();
      }
      
  • Examples

    package pers.chh3213.UDP;
    
    import org.junit.Test;
    
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    /**
     * UDPd Network programming of protocol
     */
    public class UDPTest {
    
        //Sender
        @Test
        public void sender() throws IOException {
            DatagramSocket socket = new DatagramSocket();
    
            String str = "I am UDP Sender";
            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();
        }
    }
    
    

7. URL programming

7.1 URL class

  • URL(Uniform Resource Locator): uniform resource locator, which represents the address of a resource on the Internet.
    -It is a specific URI, that is, the URL can be used to identify a resource, and also indicates how to locate the resource.

  • Through URL, we can access various network resources on the Internet, such as the most common www and ftp sites. The browser can find the corresponding files or other resources on the network by parsing the given URL.

  • The basic structure of a URL consists of five parts:
    < transport protocol > / / < host name >: < port number > / < file name > # fragment name? parameter list

    • For example:
      http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
    • #Segment name: that is, the anchor point, such as reading a novel, is directly positioned to the chapter
    • Parameter list format: parameter name = parameter value & parameter name = parameter value
  • To represent a URL, Java Net. We can initialize a URL object through the following constructor:
    -The constructor of URL class declares that it throws a non runtime exception, which must be handled. It is usually caught with a try catch statement.

  • After a URL object is generated, its properties cannot be changed, but they can be given through it
    Method to get these properties:

    package pers.chh3213.URL;
    
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class URLTest {
        public static void main(String[] args) {
            try{
                URL url = new URL("https://mp.csdn.net/#");
                System.out.println("getProtocol() :"+url.getProtocol());
                System.out.println("getHost() :"+url.getHost());
                System.out.println("getPort() :"+url.getPort());
                System.out.println("getPath() :"+url.getPath());
                System.out.println("getFile() :"+url.getFile());
                System.out.println("getQuery() :"+url.getQuery());
            }catch (MalformedURLException e){
                e.printStackTrace();
            }
        }
    }
    
    

7.2 URLConnection class for HTTP protocol

  • URL method openStream(): it can read data from the network

  • If you want to output data, for example, send some data to the server-side CGI (short for Common Gateway Interface, which is the interface between the user browser and the server-side application), you must establish a connection with the URL before reading and writing it. At this time, you need to use URLConnection.

  • URLConnection: indicates the connection to the remote object referenced by the URL. When establishing a connection with a URL, first generate the corresponding URLConnection object on a URL object through the method openConnection(). If the connection process fails, an IOException will be generated

    • URL netchinaren = new URL ("http://www.atguigu.com/index.shtml");
    • URLConnectonn u = netchinaren.openConnection( );
  • The input and output streams obtained through the URLConnection object can be compared with the existing CGI
    Program interaction.

    public Object getContent( ) throws IOException
    public int getContentLength( )
    public String getContentType( )
    public long getDate( )
    public long getLastModified( )
    public InputStream getInputStream( )throws IOException
    public OutputSteram getOutputStream( )throws IOException
    
  • Data download of Tomcat server by URL network programming

    package pers.chh3213.URL;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class URLTest2 {
        public static void main(String[] args) {
            HttpURLConnection urlConnection = null;
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL("http://127.0.0.1:8080/1.jpg");
    
                urlConnection = (HttpURLConnection) url.openConnection();
    
                urlConnection.connect();
    
                is = urlConnection.getInputStream();
                fos = new FileOutputStream("day10\\10.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();
                }
            }
        }
    }
    
    

7.3 difference between URI, URL and URN

  • Uri is a uniform resource identifier, which is used to uniquely identify a resource. The URL is a uniform resource locator, a uniform resource locator. It is a specific URI, that is, the URL can be used to identify a resource, and also indicates how to locate the resource. URN, uniform resource name, uniform resource name, identifies resources by name, such as mailto:java-net@java.sun.com . In other words, URI is an abstract and high-level concept to define unified resource identification, while URL and URN are specific ways of resource identification. Both URL and URN are URIs.
  • In the URI of Java, a URI instance can represent absolute or relative, as long as it conforms to the syntax rules of URI. The URL class not only conforms to the semantics, but also contains the information to locate the resource, so it cannot be relative.

Summary

  • Computers in the network have unique IP addresses so that different hosts can be distinguished from each other.
  • Client server is the most common network application model. A server is hardware or software that provides a specific service to its clients. A client is a user application that accesses services provided by a server. Port number is the access place for a service. It is used to distinguish multiple services on the same physical computer. Socket is used to connect client and server. Each communication session between client and server uses a different socket. TCP protocol for real
    Connection oriented sessions are now available.
  • The functions related to network in Java are defined in Java Net package. Java uses InetAddress object to represent IP address, which has two fields: host name (String) and IP address (int).
  • Class socket and ServerSocket implement the client server program based on TCP protocol. Socket is a connection between the client and the server. The details of connection creation are hidden. This connection provides a safe data transmission channel because TCP protocol can solve the problems of data loss, damage, repetition, disorder and network congestion in the transmission process. It ensures the reliable transmission of data.
  • Class URL and URLConnection provide the most advanced network applications. The location of network resources of URL represents all kinds of network resources on the Internet. Through the URL object, you can create a connection between the current application and the network resources represented by the URL, so that the current application can read the network resource data or transfer its own data to the network.

practice

Refer to: https://www.cnblogs.com/zhaoyunlong/p/13256315.html

  • 1) The server can read the local file content and send the content to the requesting client
    2) Then write a client that can send a request to the server and get the file content from the server segment

    package pers.chh3213.exercise;
    
    import org.junit.Test;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.File;
    
    public class SocketServerClientTest {
        @Test
        public void TcpTestOneClient(){
    
            Socket socket = null;
            InputStream is = null;  // Get server information
    //        ByteArrayOutputStream bos = null;
            FileOutputStream fos = null;
            try {
                socket = new Socket("127.0.0.1",1001);
                is = socket.getInputStream();
                int len;
                byte [] bytes = new byte[5];
    //            bos = new ByteArrayOutputStream();
                fos = new FileOutputStream("100.jpg");
                while ((len = is.read(bytes)) != -1){
    //                bos.write(bytes,0,len);
                    fos.write(bytes,0,len);
                }
    //            System.out.println(bos.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if(is != null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if(fos != null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
    //            if(bos != null){
    //                try {
    //                    bos.close();
    //                } catch (IOException e) {
    //                    e.printStackTrace();
    //                }
    //            }
            }
        }
    
        @Test
        public void TcpTestOneServer(){
            ServerSocket serverSocket = null;
            Socket socket = null;
            OutputStream os = null;
            FileInputStream fis = null;
            try {
                serverSocket = new ServerSocket(1001);
                socket = serverSocket.accept();
                os = socket.getOutputStream();
                int len;
                byte [] bytes = new byte[1024];
                fis = new FileInputStream(new File("1.jpg"));
                while ((len = fis.read(bytes)) != -1){
                    os.write(bytes,0,len);
    //                os.write("Lao Wang, I sent you a picture. You can enjoy it. getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(serverSocket != null){
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if(os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                if(fis != null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        
    }
    
    
  • Write an ATM server and a client. You can enter the account number and password through the client, and then use the server-side verification, and realize the functions of ATM saving, withdrawing and modifying the password

    reference resources https://blog.csdn.net/newHollow/article/details/107444563

Topics: Java network