Java network programming

Posted by Nathaniel on Tue, 04 Jan 2022 00:15:14 +0100

1. Related concepts of network

1.1 network communication

(1) Concept: data transmission between two devices is realized through network
(2) Network communication: transfer data from one device to another through the network
(3)java.net package provides a series of classes and interfaces for programmers to complete network communication

1.2 network

(1) Concept: two or more devices are connected through certain physical devices to form a network
(2) Classify the network according to its coverage:

  • LAN: minimum coverage, covering only one classroom or one computer room
  • Man: it covers a large area and can cover a city
  • Wide area network: it has the largest coverage and can cover the whole country or even the whole world. The world wide web is the representative of the wide area network

1.3 ip address

(1) Concept: used to uniquely identify each computer / host in the network
(2) View ip address: ipconfig
(3) Representation of ip address: dotted decimal XX xx. xx. xx
(4) Each decimal number range: 0 ~ 255
(5) ip address composition = network address + host address, for example: 192.168.16.69
(6) ipv6 is the next generation IP protocol designed by the Internet Engineering Task Force to replace ipv4. Its number of addresses claims to be an address for every grain of sand in the world
(7) The biggest problem of IPv4 is the limited network address resources, which seriously restricts the application and development of the Internet. The use of IPv6 can not only solve the problem of the number of network address resources, but also solve the obstacle of a variety of access devices connecting to the Internet

1.4 ipv4 address classification



especial:
127.0.0.1 indicates the local address

1.5 domain name

(1)www.baidu.com
(2) Benefits: in order to facilitate memory, solve the difficulty of recording IP
(3) Concept: Map IP addresses to domain names. How to map them here? HTTP protocol

Port number:
(1) Concept: used to identify a specific network program on a computer
(2) Representation: in integer form, the port range is 0 ~ 65535 [2 bytes represent port 0 ~ 2 ^ 16 - 1]
(3) 0 ~ 1024 has been occupied, such as ssh 22, ftp 21, SMTP 25, HTTP 80
(4) Common network program port numbers:

  • tomcat: 8080
  • mysql: 3306
  • Oracle: 1521
  • sqlserver: 1433

1.6 network communication protocol

Protocol (tcp/ip)
The abbreviation of TCP / IP (Transmission Control Protocol / Internet Protocol) is: Transmission Control Protocol / Internet Interconnection Protocol, also known as network communication protocol. This protocol is the most basic protocol of the Internet and the basis of the Internet. In short, it is composed of IP protocol at the network layer and TCP protocol at the transport layer.

1.7 network communication protocol

1.8 TCP and UDP

TCP: Transmission Control Protocol

  1. Before using TCP protocol, a TCP connection must be established to form a data transmission channel
  2. Before transmission, the method of "three times handshake" is reliable
  3. There are two processes for TCP communication: client and server
  4. A large amount of data can be transmitted in the connection
  5. After transmission, the established connection needs to be released, which is inefficient

UDP protocol: user data protocol

  1. Encapsulate the data, source and destination into packets without establishing a connection
  2. The size of each packet is limited to 64K, which is not suitable for transmitting a large amount of data
  3. It is unreliable because there is no connection
  4. At the end of sending data, there is no need to release resources (because it is not connection oriented), speed block
  5. Example: texting

2 InetAddress class

2.1 relevant methods

(1) Gets the getLocalHost of the native InetAddress object
(2) Get the IP address object getByName according to the host name / domain name of the InetAddress object
(3) Gets the hostname getHostName of the InetAddress object
(4) Get the address getHostAddress of the InetAddress object

2.2 application cases

public class API_ {
    public static void main(String[] args) throws UnknownHostException {

        //1. Get the InetAddress object of this machine
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);//LAPTOP-3D7MI4QB/192.168.230.1

        //2. Obtain the InetAddress object according to the specified host name
        InetAddress host1 = InetAddress.getByName("DESKTOP-S4MP84S");
        System.out.println("host1=" + host1);//LAPTOP-3D7MI4QB/192.168.230.1

        //3. Return the InetAddress object according to the domain name, such as www.baidu.com Com correspondence
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        System.out.println("host2=" + host2);//www.baidu.com / 110.242.68.4

        //4. Obtain the corresponding address through the InetAddress object
        String hostAddress = host2.getHostAddress();//IP 110.242.68.4
        System.out.println("host2 Corresponding ip = " + hostAddress);//110.242.68.4

        //5. Obtain the corresponding host name and / or domain name through the InetAddress object
        String hostName = host2.getHostName();
        System.out.println("host2 Corresponding host name/domain name=" + hostName); // www.baidu.com

    }
}

3 Socket

3.1 basic introduction

(1) Socket is widely used to develop network applications, so that it has become a de facto standard
(2) Socket s shall be provided at both ends of the communication, which are the communication endpoints between two machines
(3) Network communication is actually the communication between sockets
(4) Socket allows the program to treat the network connection as a stream, and the data is transmitted between the two sockets through IO
(5) Generally, the application that initiates communication actively belongs to the client, and the one waiting for communication request is the server

4 TCP network communication programming

4.1 basic introduction

(1) Network communication based on client server
(2) The bottom layer uses TCP/IP protocol
(3) Application scenario example: the client sends data, and the server accepts and displays the console
(4) TCP programming based on Socket

4.2 application case 1 (using byte stream)

(1) Write a server and a client
(2) The server listens on port 9999
(3) Connect the client to the server, send "hello,server", and then exit
(4) The server receives the information sent by the client, outputs it, and exits

/**
 * Server
 */
public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Listen on the 9999 port of this computer and wait for connection
        //   Details: no other service is listening to 9999 on this machine
        //   Details: the Server Socket can return multiple sockets through accept() [concurrency of multiple clients connecting to the server]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The server listens on port 9999 and waits for a connection..");
        //2. When no client is connected to port 9999, the program will block and wait for connection
        //   If there is a client connection, the Socket object will be returned and the program will continue

        Socket socket = serverSocket.accept();

        System.out.println("Server socket =" + socket.getClass());
        //
        //3. Through socket Getinputstream() reads the data written to the data channel by the client and displays
        InputStream inputStream = socket.getInputStream();
        //4. IO read
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));//Display the content according to the actual length read
        }
        //5. Close the stream and socket
        inputStream.close();
        socket.close();
        serverSocket.close();//close

    }
}
/**
 * client
 * Send "hello, server" to the server
 */
public class SocketTCP01Client {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Connect the server (ip, port)
        //Interpretation: connect to the 9999 port of the local machine. If the connection is successful, return the Socket object
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("client socket return=" + socket.getClass());
        //2. After connecting, generate a Socket through Socket getOutputStream()
        //   Get the output stream object associated with the socket object
        OutputStream outputStream = socket.getOutputStream();
        //3. Write data to the data channel through the output stream
        outputStream.write("hello, server".getBytes());
        //4. The stream object and socket must be closed
        outputStream.close();
        socket.close();
        System.out.println("Client exit.....");
    }
}

4.3 application case 2 (using byte stream)

(1) Write a server and a client
(2) The server listens on port 9999
(3) The client connects to the server, sends "hello,server", receives the "hello,client" sent back by the server, and then exits
(4) The server receives the information sent by the client, outputs it, sends "hello,client", and then exits

/**
 * Server
 */
@SuppressWarnings({"all"})
public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Listen on the 9999 port of this computer and wait for connection
        //   Details: no other service is listening to 9999 on this machine
        //   Details: the Server Socket can return multiple sockets through accept() [concurrency of multiple clients connecting to the server]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The server listens on port 9999 and waits for a connection..");
        //2. When no client is connected to port 9999, the program will block and wait for connection
        //   If there is a client connection, the Socket object will be returned and the program will continue

        Socket socket = serverSocket.accept();

        System.out.println("Server socket =" + socket.getClass());
        //
        //3. Through socket Getinputstream() reads the data written to the data channel by the client and displays
        InputStream inputStream = socket.getInputStream();
        //4. IO read
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));//Display the content according to the actual length read
        }
        //5. Obtain the output stream associated with the socket
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello, client".getBytes());
        //   Set end tag
        socket.shutdownOutput();

        //6. Close the stream and socket
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();//close

    }
}
/**
 * client
 * Send "hello, server" to the server
 */
@SuppressWarnings({"all"})
public class SocketTCP02Client {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Connect the server (ip, port)
        //Interpretation: connect to the 9999 port of the local machine. If the connection is successful, return the Socket object
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("client socket return=" + socket.getClass());
        //2. After connecting, generate a Socket through Socket getOutputStream()
        //   Get the output stream object associated with the socket object
        OutputStream outputStream = socket.getOutputStream();
        //3. Write data to the data channel through the output stream
        outputStream.write("hello, server".getBytes());
        //   Set end tag
        socket.shutdownOutput();

        //4. Get the input stream associated with socket Read data (bytes) and display
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1) {
            System.out.println(new String(buf, 0, readLen));
        }

        //5. The stream object and socket must be closed
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("Client exit.....");
    }
}

4.4 application case 3 (using character stream)

(1) Write a server and a client
(2) The server listens on port 9999
(3) The client connects to the server, sends "hello,server", receives the "hello,client" sent back by the server, and then exits
(4) The server receives the information sent by the client, outputs it, sends "hello,client", and then exits

/**
 * The server uses character stream to read and write
 */
@SuppressWarnings({"all"})
public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Listen on the 9999 port of this computer and wait for connection
        //   Details: no other service is listening to 9999 on this machine
        //   Details: the Server Socket can return multiple sockets through accept() [concurrency of multiple clients connecting to the server]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The server listens on port 9999 and waits for a connection..");
        //2. When no client is connected to port 9999, the program will block and wait for connection
        //   If there is a client connection, the Socket object will be returned and the program will continue

        Socket socket = serverSocket.accept();

        System.out.println("Server socket =" + socket.getClass());
        //
        //3. Through socket Getinputstream() reads the data written to the data channel by the client and displays
        InputStream inputStream = socket.getInputStream();
        //4. For IO reading, use character stream, and use InputStreamReader to convert inputStream into character stream
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);//output

        //5. Obtain the output stream associated with the socket
        OutputStream outputStream = socket.getOutputStream();
       //    Reply to a message using a character output stream
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello client Character stream");
        bufferedWriter.newLine();// Insert a line break to indicate the end of the reply
        bufferedWriter.flush();//Note that manual flush is required


        //6. Close the stream and socket
        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();//close

    }
}
/**
 * The client sends "hello, server" to the server and uses the character stream
 */
@SuppressWarnings({"all"})
public class SocketTCP03Client {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Connect the server (ip, port)
        //Interpretation: connect to the 9999 port of the local machine. If the connection is successful, return the Socket object
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("client socket return=" + socket.getClass());
        //2. After connecting, generate a Socket through Socket getOutputStream()
        //   Get the output stream object associated with the socket object
        OutputStream outputStream = socket.getOutputStream();
        //3. Write data to the data channel through the output stream and use the character stream
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello, server Character stream");
        bufferedWriter.newLine();//Insert a new line character to indicate the end of the written content. Note that the other party is required to use readLine()!!!!
        bufferedWriter.flush();// If the character stream is used, it needs to be refreshed manually, otherwise the data will not be written to the data channel


        //4. Get the input stream associated with socket Read data (characters) and display
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        //5. The stream object and socket must be closed
        bufferedReader.close();//Turn off outer flow
        bufferedWriter.close();
        socket.close();
        System.out.println("Client exit.....");
    }
}

4.5 application case 4

(1) Write a server and a client
(2) The server listens on port 8888
(3) The client connects to the server and sends a picture E:\a.png
(4) The server receives the picture sent by the client, saves it to src, sends "received picture", and then exits
(5) The client receives the "received picture" sent by the server and then exits
(6) This program requires streamutils Java, we use it directly

/**
 * @Author: Xie Jiasheng
 * @Date: 2021/12/30-12-30-11:02
 * @Version: 1.0
 * File upload server
 */
public class TCPFileUploadServer {
    //This is a main method, which is the entry of the program:
    public static void main(String[] args) throws Exception {

        //1. Listen to 8888 port
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("The server is listening on port 8888 and waiting for connection...");
        //2. Wait for connection
        Socket socket = serverSocket.accept();
        //3. Obtain the data sent by the client
        //  Get the input stream through Socket
        InputStream inputStream = socket.getInputStream();
        //Convert file to byte array
        byte[] bytes = StreamUtils.streamToByteArray(inputStream);
        //Write the bytes array to the specified path to get a file
        String destFilePath = "src\\net\\upload\\a.jpg";
        FileOutputStream fileOutputStream = new FileOutputStream(destFilePath);
        fileOutputStream.write(bytes);
        //4. Reply to the client: "file received"
        //  Get the output stream (character) through socket
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("File received~~~");
        bufferedWriter.flush();//Refresh content to data channel
        bufferedWriter.newLine();//Set write end flag

        System.out.println("Completion of server~");


        //5. Close the flow
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();

    }
}
/**
 * @Author: Xie Jiasheng
 * @Date: 2021/12/30-12-30-11:03
 * @Version: 1.0
 * File upload client
 */
public class TCPFileUploadClient {
    //This is a main method, which is the entry of the program:
    public static void main(String[] args) throws Exception {

        //1. The client connects to the server 8888 to get the Socket object
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        //2. / / create an input stream to read disk files
        String filePath = "e:\\a.jpg";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
        //bytes is the byte array corresponding to filePath
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //3. Obtain the output stream through socket and send bytes data to the server
        OutputStream outputStream = socket.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        bos.write(bytes);//Write the contents of the byte array corresponding to the file to the data channel
        socket.shutdownOutput();//Sets the end flag for writing data
        bis.close();

        //=====Receive messages replied from the server=====

        //4. Accept the message replied by the server
        InputStream inputStream = socket.getInputStream();
        //Use the StreamUtils method to directly convert the content read by inputStream into a string
        String s = StreamUtils.streamToString(inputStream);
        System.out.println(s);

        System.out.println("Client exit after live...");

        //5. Close the flow and release resources
        bos.close();
        socket.close();

    }
}
/**
 * This class is used to demonstrate how to read and write about streams
 *
 */
public class StreamUtils {
	/**
	 * Function: convert the input stream into byte [], that is, you can read the contents of the file into byte []
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public static byte[] streamToByteArray(InputStream is) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();//Create output stream object
		byte[] b = new byte[1024];//Byte array
		int len;
		while((len=is.read(b))!=-1){//Cyclic reading
			bos.write(b, 0, len);//Write the read data to bos	
		}
		byte[] array = bos.toByteArray();//Then convert bos to a byte array
		bos.close();
		return array;
	}
	/**
	 * Function: convert InputStream to String
	 * @param is
	 * @return
	 * @throws Exception
	 */
	
	public static String streamToString(InputStream is) throws Exception{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder builder= new StringBuilder();
		String line;
		while((line=reader.readLine())!=null){
			builder.append(line+"\r\n");
		}
		return builder.toString();
		
	}

}

4.6 netstat instruction

(1) netstat -an can view the current host network, including port listening and network connection
(2) netstat -an | more can be displayed in pages
(3) netstat -anb can check which program is listening / connecting [needs to be run as administrator]
(4) It is required to execute win + r under dos console
explain:
(1) Linstening indicates that a port is listening
(2) If an external program (client) is connected to the port, a connection information is displayed
(3) You can enter ctrl + c to exit the command


4.7 unknown secrets of TCP network communication


(1) When the client connects to the server, in fact, the client communicates with the server through a port allocated by TCP/IP, which is uncertain and random
(2) Schematic diagram
(3) Program validation + netstat

5 UDP network communication programming [understand]

5.1 basic introduction

(1) Classes datagram socket and datagram socket [packet / datagram] implement network programs based on UDP protocol
(2) 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
(3) The datagram pack 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
(4) Each datagram in UDP protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver

5.2 basic process

(1) Two classes / objects of the core
Datagram socket and datagram packet
(2) Establish sending end and receiving end (there is no concept of server and client)
(3) Before sending data, establish datagram packet
(4) Call the sending and receiving methods of DatagramSocket
(5) Close datagram socket

5.3 application cases

(1) Write A receiver A and A sender B
(2) Receiving terminal A waits for receiving data at port 9999
(3) Sender B sends data "hello, eat hot pot tomorrow ~" to receiver A
(4) Receiver A receives the data sent by sender B, replies "OK, see you tomorrow", and then exits
(5) The sender accepts the reply data and then exits


/**
 * UDP receiving end
 */
public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        //1. Create a DatagramSocket object to receive data in 9999
        DatagramSocket socket = new DatagramSocket(9999);
        //2. Build a DatagramPacket object and prepare to receive data
        //   When I explained the UDP protocol earlier, I said that the maximum size of a packet is 64k
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //3. Call the receiving method to transfer the datagram packet object transmitted through the network
        //   Populate to packet object
        //Tip: when a data packet is sent to the 9999 port of this machine, the data will be received
        //   If no packet is sent to the local 9999 port, the wait will be blocked
        System.out.println("receiving end A Waiting to receive data..");
        socket.receive(packet);

        //4. You can unpack the packet, take out the data and display it
        int length = packet.getLength();//Length of data bytes actually received
        byte[] data = packet.getData();//Data received
        String s = new String(data, 0, length);
        System.out.println(s);


        //===Reply to terminal B
        //Encapsulate the data to be sent into the datagram packet object
        data = "well, See you tomorrow.".getBytes();
        //Description: encapsulated datagram packet object, data content byte array, data Length, host (IP), port
        packet =
                new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 9998);

        socket.send(packet);//send out

        //5. Close resources
        socket.close();
        System.out.println("A End exit...");

    }
}
/**
 * Sender B = = = = > can also receive data
 */
@SuppressWarnings({"all"})
public class UDPSenderB {
    public static void main(String[] args) throws IOException {

        //1. Create DatagramSocket object and prepare to receive data on port 9998
        DatagramSocket socket = new DatagramSocket(9998);

        //2. Encapsulate the data to be sent into the datagram packet object
        byte[] data = "hello Have hot pot tomorrow~".getBytes(); //

        //Description: encapsulated datagram packet object, data content byte array, data Length, host (IP), port
        DatagramPacket packet =
                new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 9999);

        socket.send(packet);

        //3. = = = receive the information replied from terminal A
        //(1) Build a DatagramPacket object and prepare to receive data
        //   When I explained the UDP protocol earlier, I said that the maximum size of a packet is 64k
        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        //(2) Call the receiving method to transfer the DatagramPacket object over the network
        //   Populate to packet object
        //Tip: when a data packet is sent to the 9998 port of this machine, the data will be received
        //   If no packet is sent to the local port 9998, the wait will be blocked
        socket.receive(packet);

        //(3) You can unpack the packet, take out the data, and display it
        int length = packet.getLength();//Length of data bytes actually received
        data = packet.getData();//Data received
        String s = new String(data, 0, length);
        System.out.println(s);

        //close resource
        socket.close();
        System.out.println("B End exit");
    }
}

6 operation in this chapter

6.1 programming problem (TCP)

(1) Using character stream, write a client program and server program
(2) The client sends "name". After the server receives it, it returns "I'm nova". Nova is your own name
(3) The client sends a "hobby", and the server returns "write Java program" after receiving it
(4) Not these two questions, reply "what did you say?"
Question: at present, we can only ask once and then push out. How can we ask many times? - > While - > chat

/**
 * The server uses character stream to read and write
 */
@SuppressWarnings({"all"})
public class Homework01Server {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Listen on the 9999 port of this computer and wait for connection
        //   Details: no other service is listening to 9999 on this machine
        //   Details: the Server Socket can return multiple sockets through accept() [concurrency of multiple clients connecting to the server]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The server listens on port 9999 and waits for a connection..");
        //2. When no client is connected to port 9999, the program will block and wait for connection
        //   If there is a client connection, the Socket object will be returned and the program will continue

        Socket socket = serverSocket.accept();

        //
        //3. Through socket Getinputstream() reads the data written to the data channel by the client and displays
        InputStream inputStream = socket.getInputStream();
        //4. For IO reading, use character stream, and use InputStreamReader to convert inputStream into character stream
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        String answer = "";
        if ("name".equals(s)) {
            answer = "I'm Han Shunping";
        } else if("hobby".equals(s)) {
            answer = "to write java program";
        } else {
            answer = "What are you talking about";
        }


        //5. Obtain the output stream associated with the socket
        OutputStream outputStream = socket.getOutputStream();
        //    Reply to a message using a character output stream
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write(answer);
        bufferedWriter.newLine();// Insert a line break to indicate the end of the reply
        bufferedWriter.flush();//Note that manual flush is required


        //6. Close the stream and socket
        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();//close

    }
}
/**
 * client
 */
@SuppressWarnings({"all"})
public class Homework01Client {
    public static void main(String[] args) throws IOException {
        //thinking
        //1. Connect the server (ip, port)
        //Interpretation: connect to the 9999 port of the local machine. If the connection is successful, return the Socket object
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);

        //2. After connecting, generate a Socket through Socket getOutputStream()
        //   Get the output stream object associated with the socket object
        OutputStream outputStream = socket.getOutputStream();
        //3. Write data to the data channel through the output stream and use the character stream
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        //Read the user's question from the keyboard
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter your question");
        String question = scanner.next();

        bufferedWriter.write(question);
        bufferedWriter.newLine();//Insert a new line character to indicate the end of the written content. Note that the other party is required to use readLine()!!!!
        bufferedWriter.flush();// If the character stream is used, it needs to be refreshed manually, otherwise the data will not be written to the data channel


        //4. Get the input stream associated with socket Read data (characters) and display
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        //5. The stream object and socket must be closed
        bufferedReader.close();//Turn off outer flow
        bufferedWriter.close();
        socket.close();
        System.out.println("Client exit.....");
    }
}

6.2 programming questions (UDP)

(1) Write A receiver A and A sender B, which are completed using UDP protocol
(2) The receiving end waits for receiving data at port 8888
(3) The sender sends data to the receiver. "What are the four masterpieces?"
(4) After receiving the question sent by the sender, the receiver returns "the four famous works are journey to the west, the water margin, the romance of the Three Kingdoms and a dream of Red Mansions". Otherwise, what?
(5) Program exit at receiver and sender

/**
 * UDP receiving end
 */
@SuppressWarnings({"all"})
public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        //1. Create a DatagramSocket object to receive data on 8888
        DatagramSocket socket = new DatagramSocket(8888);
        //2. Build a DatagramPacket object and prepare to receive data
        //   When I explained the UDP protocol earlier, I said that the maximum size of a packet is 64k
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //3. Call the receiving method to transfer the datagram packet object transmitted through the network
        //   Populate to packet object
        System.out.println("Waiting for reception at the receiving end ");
        socket.receive(packet);

        //4. You can unpack the packet, take out the data and display it
        int length = packet.getLength();//Length of data bytes actually received
        byte[] data = packet.getData();//Data received
        String s = new String(data, 0, length);
        //Determine what the received information is
        String answer = "";
        if("What are the four famous works".equals(s)) {
            answer = "Four masterpieces <<The Dream of Red Mansion>> <<Three Kingdoms demonstration>> <<Journey to the West>> <<Water Margin>>";
        } else {
            answer = "what?";
        }


        //===Reply to terminal B
        //Encapsulate the data to be sent into the datagram packet object
        data = answer.getBytes();
        //Description: encapsulated datagram packet object, data content byte array, data Length, host (IP), port
        packet =
                new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 9998);

        socket.send(packet);//send out

        //5. Close resources
        socket.close();
        System.out.println("A End exit...");

    }
}
/**
 * Sender B = = = = > can also receive data
 */
@SuppressWarnings({"all"})
public class Homework02SenderB {
    public static void main(String[] args) throws IOException {

        //1. Create DatagramSocket object and prepare to receive data on port 9998
        DatagramSocket socket = new DatagramSocket(9998);

        //2. Encapsulate the data to be sent into the datagram packet object
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter your question: ");
        String question = scanner.next();
        byte[] data = question.getBytes(); //

        //Description: encapsulated datagram packet object, data content byte array, data Length, host (IP), port
        DatagramPacket packet =
                new DatagramPacket(data, data.length, InetAddress.getByName("192.168.12.1"), 8888);

        socket.send(packet);

        //3. = = = receive the information replied from terminal A
        //(1) Build a DatagramPacket object and prepare to receive data
        //   When I explained the UDP protocol earlier, I said that the maximum size of a packet is 64k
        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        //(2) Call the receiving method to transfer the DatagramPacket object over the network
        //   Populate to packet object
        //Teacher's note: when a data packet is sent to the 9998 port of this machine, the data will be received
        //   If no packet is sent to the local port 9998, the wait will be blocked
        socket.receive(packet);

        //(3) You can unpack the packet, take out the data, and display it
        int length = packet.getLength();//Length of data bytes actually received
        data = packet.getData();//Data received
        String s = new String(data, 0, length);
        System.out.println(s);

        //close resource
        socket.close();
        System.out.println("B End exit");
    }
}

6.3 programming questions

(1) Write client program and server program
(2) The client can input a music file name, such as high mountains and flowing water. After receiving the music name, the server can return the music file to the client. If the server does not have this file, it can return a default music.
(3) After the client receives the file, save it to the local e:\
(4) The program can use streamutils java

/**
 * Write the server for file download first
 */
public class Homework03Server {
    public static void main(String[] args) throws Exception {

        //1 monitor 9999 port
        ServerSocket serverSocket = new ServerSocket(9999);
        //2. Wait for the client to connect
        System.out.println("The server listens on port 9999 and waits for files to be downloaded");
        Socket socket = serverSocket.accept();
        //3. Read the file name sent by the client to download
        //  Here, while is used to read the file name, considering the large data sent by the client in the future
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        String downLoadFileName = "";
        while ((len = inputStream.read(b)) != -1) {
            downLoadFileName += new String(b, 0 , len);
        }
        System.out.println("The client wants to download the file name=" + downLoadFileName);

        //There are two files on the server, nameless Mp3 high mountains and flowing water mp3
        //If the customer downloads a high mountain and flowing water, we will return the file, otherwise we will return it to anonymous mp3

        String resFileName = "";
        if("High mountains and flowing water".equals(downLoadFileName)) {
            resFileName = "src\\High mountains and flowing water.mp3";
        } else {
            resFileName = "src\\unknown.mp3";
        }

        //4. Create an input stream and read the file
        BufferedInputStream bis =
                new BufferedInputStream(new FileInputStream(resFileName));

        //5. Use the tool class StreamUtils to read the file into a byte array

        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //6. Get the output stream associated with the Socket
        BufferedOutputStream bos =
                new BufferedOutputStream(socket.getOutputStream());
        //7. Write to the data channel and return to the client
        bos.write(bytes);
        socket.shutdownOutput();//It's crucial

        //8 close related resources
        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("Server exit...");

    }
}
/**
 * Client for file download
 */
public class Homework03Client {
    public static void main(String[] args) throws Exception {


        //1. Receive user input and specify the download file name
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the download file name");
        String downloadFileName = scanner.next();

        //2. The client connects to the server and is ready to send
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //3. Obtain the output stream associated with the Socket
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(downloadFileName.getBytes());
        //Sets the end of write flag
        socket.shutdownOutput();

        //4. Read the file (byte data) returned by the server
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //5. Get an output stream and prepare to write bytes to the disk file
        //For example, what you download is high mountains and flowing water = > what you download is high mountains and flowing water mp3
        //    What you download is 123 = > what you download is nameless Mp3 file name 123 mp3
        String filePath = "e:\\" + downloadFileName + ".mp3";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(bytes);

        //6. Close related resources
        bos.close();
        bis.close();
        outputStream.close();
        socket.close();

        System.out.println("After downloading the client, exit correctly..");


    }
}
/**
 * This class is used to demonstrate how to read and write about streams
 *
 */
public class StreamUtils {
	/**
	 * Function: convert input stream into byte []
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public static byte[] streamToByteArray(InputStream is) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();//Create output stream object
		byte[] b = new byte[1024];
		int len;
		while((len=is.read(b))!=-1){
			bos.write(b, 0, len);	
		}
		byte[] array = bos.toByteArray();
		bos.close();
		return array;
	}
	/**
	 * Function: convert InputStream to String
	 * @param is
	 * @return
	 * @throws Exception
	 */
	
	public static String streamToString(InputStream is) throws Exception{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder builder= new StringBuilder();
		String line;
		while((line=reader.readLine())!=null){
			builder.append(line+"\r\n");
		}
		return builder.toString();
		
	}

}

Topics: Java network Network Protocol