The first day of learning socket communication
First of all, we need to understand why socket communication is necessary. It allows two computers to transmit information to each other.
The principle of socket communication is as follows:
The main three steps are as follows:
Server listening, client request, connection confirmation.
Server listening: the server socket does not locate the specific client socket, but is in the state of waiting for connection to monitor the network state in real time.
Client request: refers to the connection request made by the socket of the client. The target to be connected is the socket of the server. Therefore, the socket of the client must first describe the socket of the server to which it is connected, point out the address and port number of the server socket, and then make a connection request to the server socket.
Connection confirmation: when the server socket hears or receives the connection request of the client socket, it responds to the request of the client socket, establishes a new thread, and sends the description of the server socket to the client. Once the client confirms the description, the connection is established. The server socket continues to be in the listening state and continues to receive connection requests from other client sockets.
Specific process
Server side:
- Instantiate a SeverSocket object with the specified port. The server can use this port to listen for connection requests from clients.
- Call the accept() method of ServerSocket to cause blocking during connection waiting and listen for connection requests sent from the port.
- Use the Socket object of the client returned by the accept method to read and write IO.
- Close open streams and Socket objects.
client:
- Instantiate the Socket object with the IP address and port number of the server.
- Call the connect method to connect to the server.
- . obtain the stream on the Socket and encapsulate the stream into the instance of BufferedReader/PrintWriter for reading and writing
- Use getInputStream and getOutputStream methods provided by Socket to send data stream to the server through IO stream object
- Close the open stream and Socket.
package test1111; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import org.junit.jupiter.api.Test; public class SocketTest { //Client code @Test public void client() throws Exception { // Define the IP address and port of the server to be connected String host = "127.0.0.1"; int port = 9001; // 1. Create a client socket, specify the server address host and port, and establish a connection with the server Socket socket = new Socket(host, port); // 2. After establishing the connection, obtain the output stream and send information to the server OutputStream outputStream = socket.getOutputStream();//Byte output stream String message = "Hello"; outputStream.write(message.getBytes("UTF-8")); //The high-speed server has sent data through shutdown output, and can only accept data later socket.shutdownOutput(); //3. Get the input stream and read the server-side response information InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[1024]; int len; StringBuilder sb = new StringBuilder(); while ((len = inputStream.read(bytes)) != -1) { //Note that the coding format must be specified. The sender and receiver must be unified. It is recommended to use UTF-8 sb.append(new String(bytes, 0, len,"UTF-8")); } System.out.println("get message from server: " + sb); //4. Close resource inputStream.close(); outputStream.close(); socket.close(); } //Server side code @Test public void server() throws Exception{ int port = 9001;//Specify the listening port. The port number is in the range of 1024-65535 //1. Create a server-side Socket, i.e. ServerSocket, specify the bound port and listen to this port ServerSocket server = new ServerSocket(port); //The server will wait for the connection to arrive System.out.println("server Will be waiting for the connection to arrive"); //2. Call the accept() method to start listening and wait for the client to connect Socket socket = server.accept(); //3. Get the input stream and read the client information // After the connection is established, obtain the input stream from the socket and establish a buffer for reading InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[1024]; int len; StringBuilder sb = new StringBuilder(); //Only when the client closes its output stream can the server get the - 1 at the end while ((len = inputStream.read(bytes)) != -1) { // Note that the coding format must be specified. The sender and receiver must be unified. It is recommended to use UTF-8 sb.append(new String(bytes, 0, len, "UTF-8")); } System.out.println("get message from client: " + sb); //4. Get the output stream and respond to the client's request OutputStream outputStream = socket.getOutputStream(); outputStream.write("Hello Client,I get the message.".getBytes("UTF-8")); //5. Close resource inputStream.close(); outputStream.close(); socket.close(); server.close(); } }
The above program uses Test unit Test. We need to run server-side code in the unit first, and then run client-side code.