Java Network Programming

Keywords: Programming socket network Java

Use of the Internet Access class

1. Overview

  1. Computer network:

    • Interconnect computers distributed in different geographic areas with specialized external equipment using 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.
  2. The purpose of network programming is to exchange and communicate with other computers directly or indirectly through network protocols.

  3. Two issues to be solved in network communication

    • How to accurately locate one or more hosts on a network; locate specific applications on hosts
    • How to transfer data reliably and efficiently when a host is found

2. Network Communication Elements

  • Solution 1: IP and port number
  • Solution 2: Provide network communication protocol: TCP/IP reference model (application layer, transport layer, network layer, physical + data link layer)

Network Communication Protocol

Communication process

3. Communication Element One: IP and Port Number

3.1 Understanding of IP

  • IP: Uniquely identifies the computer on the Internet (communication entity)
  • Use the InetAddress class to represent IP in Java
  • IP Classification: IPv4 and IPv6; World Wide Web and LAN
  • Domain name: Resolve a domain name to an IP address through a domain name resolution server www.baidu.com www.mi.com www.jd.com
  • Domain Name Resolution: Domain names are 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 to an IP address so that a connection can be established with the host.
  • Local loop address: 127.0.0.1 corresponds to: localhost

3.2 Port number:

Used to identify processes running on the computer.

  • Requirements: Different processes have different port numbers
  • Range: specified as a 16-bit integer 0~65535.
  • Classification:
    • Accepted ports: 0~1023. Occupied by predefined service communications (e.g., HTTP Occupies Port 80, FTP Occupies Port 21, TeInet Occupies Port 23).
    • Registration ports: 1024~49151. Assigned to user processes or applications.(For example, Tomcat takes up port 8080, MSQL takes up port 3306, Oracle takes up port 1521, etc.).
    • Dynamic private ports: 49152~65535.

The combination of port number and IP address results in a network socket: Socket

3.3 InetAddress class

An object of this class represents a specific IP address

3.2.1 Instantiation

getByName(String host) /getLocalHost()

3.2.2 Common Methods

getHostName() / getHostAddress()

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.baidu.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 Communication Protocol

4.1 Hierarchical Model

4.2 Differences between TCP and UDP

TCP protocol:

  • Before using TCP protocol, TCP connection must be established to form transmission data channel

  • Before transmission, it is reliable to use "three-time handshake" method and point-to-point communication

  • There are two application processes for TCP protocol communication: client and server.

  • Large amount of data can be transferred in a connection

  • When the transfer is complete, the established connection needs to be released, which is inefficient

UDP protocol:

  • Encapsulate data, source, and purpose into a package without establishing a connection

  • Limit the size of each datagram to 64K

  • Sending is unreliable because the receiver receives and does not confirm whether the other party is ready or not

  • Can broadcast

  • No resources need to be released at the end of sending data, less overhead and faster

4.3 TCP three and four handshakes

5. Socket Socket

  • Developing network applications using sockets has been so widely adopted that it has become a de facto standard.

  • A uniquely identifiable P address and port number on a network are combined to form a uniquely identifiable identifier socket.

  • Socket s are required at both ends of the communication and are the endpoints of communication between two machines.

  • Network communication is actually communication between Socket s

  • Sockets allow programs to view a network connection as a stream, and data is transferred through IO between two Sockets.

  • In general, the application that initiates communication actively belongs to the client, and the server waits for the communication request

  • Socket Classification

    • Stream socket: Use TCP to provide a dependent byte stream service
    • Datagram socket: Provide best effort datagram services using UDP

3. TCP Network Programming

Socket-based programming in Java is divided into client and server

TCP-based Socket communication model

1. TCP programming based on Socke

1.1 Client Socket Work Process

  • Create a Socket: Construct a Scket class object based on the P address or port number of the specified server.If the server responds, a client-to-server communication line is established.If the connection fails, an exception occurs.

  • Open input and output streams connected to Socket s: get input streams using getInputstream() method, get output streams using getOutputStream() method, and transfer data

  • Read/write Socket s according to a protocol: read the information put on the line by the server through the input stream (but cannot read the information put on the line by yourself), and write the information to the thread through the output stream

  • Close Socket: Disconnect client from server, release line

Explain:

  • Client programs can create objects using the Socket class, which automatically initiates a connection to the server.

  • The constructor of a Socket is:

    • Socket(String host, int port) throws UnknownHostException, EXCeption: Initiates a TCP connection to the server (domain name is host, port number) and creates a Socket object if successful, otherwise throws an exception.
    • Socket(InetAddress address, int port)throws IOException: Initiates a connection based on the IP address represented by the InetAddress object and the port number port
  • The process by which a client establishes a socketAtClient object is to make a socket connection request to the server

1.2 Server-side Socket s:

  • Call ServerSocket(int port): Create a server-side socket and bind it to the specified port.Used to listen for client requests.

  • Call accept0(): Listens for connection requests, accepts connections, and returns a communication socket object if a client requests a connection.

  • Call getOutputStream() and getInputStream() of the Socket class object: Get the output and input streams, and start sending and receiving network data.

  • Close ServerSocket and Socket Objects: Client access ends, communication sockets are closed.

Explain:

  • The ServerSocket object is responsible for waiting for a client to request a socket connection, similar to a salesperson in a window in a post office.That is, the server must first create a Server Socket object that waits for the client to request a socket connection.

  • The so-called "receive" client's socket request is that the accept() method returns a Socket object

1.3 Code Sample

Example 1: Client sends information to server, which displays data on console

public class TCPTest1 {

    //Client
    @Test
    public void client()  {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1. Create a Socket object indicating the server-side ip and port number
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2. Get an output stream for output data
            os = socket.getOutputStream();
            //3. Writing out data
            os.write("Hello, I'm a client mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Closing 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 server-side ServerSocket, specifying your own port number
            ss = new ServerSocket(8899);
            //2. Call accept() to receive socket s from the client
            socket = ss.accept();
            //3. Get input stream
            is = socket.getInputStream();

            //It is not recommended to write like this, there may be garbage
            //        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 data from 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 a file to the server, which saves the file locally.

public class TCPTest2 {

    /*
    Exceptions involved here should be handled using 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();
    }

    /*
    Exceptions involved here should be handled using 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 a file from the client to the server, which saves it locally.And returns "Send Successfully" to the client.

public class TCPTest3 {

    /*
        Exceptions involved here should be handled using 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();
    }

    /*
    Exceptions involved here should be handled using 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. Server-side feedback to client
        OutputStream os = socket.getOutputStream();
        os.write("Hello, Beauty, I've received the photo, it's very beautiful!".getBytes());

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

    }
}

IV. UDP Network Programming

1. Brief description

  • Classes DatagramSocket and DatagramPacket implement network programs based on the DP protocol.

  • UDP datagrams are sent and received through the datagram socket DatagramSocket. The system does not guarantee that UDP datagrams will reach their destination safely or when they will arrive.

  • The DatagramPacket object encapsulates a UDP datagram that contains the IP address and port number of the sender and the IP address and port number of the receiver.

  • Each datagram in the 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 a courier package.

2. Common methods of the DatagramSocket class

3. Use of the DatagramSocket class

Technological process:

  1. DatagramSocket and DatagramPacket

  2. Create Sender, Receiver

  3. Create data packages

  4. Invoke send and receive methods of Socket s

  5. Close Socket

Note: Sender and Receiver are two separate running programs

Code example:

public class UDPTest {

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

        DatagramSocket socket = new DatagramSocket();



        String str = "I am UDP Missile sent in mode";
        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();
    }
}

V. URL Programming

  • URL(Uniform Resource Locator): A uniform resource locator that represents the address of a resource on the Internet.

  • It is a specific URI, that is, a URL can be used to identify a resource, and it also indicates how to locate the resource.

  • URLs allow us to access various network resources on the Internet, such as the most common www, ftp sites.Browsers can find files or other resources on the network by resolving a given URL

  • The basic structure of a URL consists of five parts: <Transport Protocol>://<Host Name>:<Port Number>/<File Name>#Fragment Name?A list of parameters such as: http://192.168.1.100:8080/helloworld/indexjsp#a?username=shkstart&password=123 #fragment name: that is, anchor point, such as reading a novel, directly positioned in the format of chapter parameter list: parameter name = parameter value &parameter name = parameter value...

1. URL Class

1.1 Constructor

To represent URLs, class URLs are implemented in java.net.We can initialize a URL object with the constructor below

  • public URL(String spec): A URL object can be constructed from a string representing the URL address.For example: URL url = new URL (" http://www.baidu.com/");
  • public URL(URL context,String spec): Construct a URL object from base URLs and relative URLs, for example: URL downloadeUrl = new URL (url,"download.html");
  • public URL(String protocol,String host,String file); for example, new URL("http", " www.baidu.com",80,"download.html");
  • public URL(String protocol,String host,int port,String file); for example, new URL("http", " www.baidu.com",80,"download.html");

Note: The constructors of the URL class all declare that a non-runtime exception was thrown and must be handled, usually by a try-catch statement.

1.2 Method

  • public String getProtocol() Gets the protocol name of the URL
  • public String getHost() Gets the host name of the URL
  • public String getPort() Gets the port number of the URL
  • public String getPath() Gets the file path of the URL
  • public String getFile() Gets the file name of the URL
  • public String getQuery() Gets the query name of the URL

Code Samples

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();
        }

    }
}

Posted by j7n5u on Mon, 04 May 2020 23:00:20 -0700