JAVA Deepening Chapter_37 – TCP Communication Implementation and Project Cases

TCP communication implementation and project cases

TCP communication implementation principle

We mentioned that the TCP protocol is connection-oriented, and the client and server must establish a connection during communication. In network communication, the program that actively initiates communication for the first time is called the client program, or client for short, and the program that waits for the connection in the first communication is called the server program, or server for short. . Once communication is established, the client and server are exactly the same and there is no essential difference.

Request-response pattern:

  • Socket class: Send TCP messages.
  • ServerSocket class: Create a server.

Socket is a data exchange mechanism between processes. These processes can be on the same machine or on different machines connected by a network. In other words, sockets function as communication endpoints. A single socket is an endpoint, while a pair of sockets forms a bidirectional communication channel, allowing unaffiliated processes to exchange data locally or over the network. Once a socket connection is established, data can be sent in both directions or in one direction on the same or different systems until one of the endpoints closes the connection. A socket is associated with a host address and a port address. The host address is the IP address of the host where the client or server program is located. The port address refers to the communication port of the host used by the client or server program.

In the client and server, create independent Sockets respectively, and connect the two Sockets through the Socket properties. In this way, the client and the server communicate using the input and output streams through the connection established by the socket.

TCP/IP sockets are the most reliable bidirectional streaming protocol and any amount of data can be sent using TCP/IP.

In fact, a socket is just a numbered port on your computer. If the sending and receiving computers determine the ports, they can communicate.

Communication diagram between client and server:

Simple process of TCP/IP communication connection:

The TCP/IP software on computer A sends a message containing a port number to computer B. The TCP/IP software on computer B receives the message and checks to see if there is a program it knows is receiving the message on that port. If so, he hands the message over to this program.

For a program to run effectively, it must have a client and a server.

Programming sequence through Socket:

  1. Create a server ServerSocket. When creating, define the listening port of the ServerSocket (receive messages from the client on this port)
  2. ServerSocket calls the accept() method to put it in a blocking state.
  3. Create a client Socket and set the server’s IP and port.
  4. The client issues a connection request and establishes a connection.
  5. Obtain the InputStream and OutputStream of the server and client Sockets respectively.
  6. Use Socket and ServerSocket for data transmission.
  7. Close the stream and Socket.

TCP communication entry case

Create server
1public class BasicSocketServer {<!-- -->
2 public static void main(String[] args) {<!-- -->
3

4 System.out.println("The server is started and waiting to be monitored...");
5 //Create ServerSocket
6 try(ServerSocket ss =new ServerSocket(8888);
7 //Listen to port 8888, and the thread will be blocked at this time.
8 Socket socket = ss.accept();
9 //After the connection is successful, the Socket object corresponding to the client will be obtained and the thread blocking will be released.
10 //Get the message sent by the client through the input stream object in the Socket object corresponding to the client.
      BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))
12 ){<!-- -->
13
14 System.out.println(br.readLine());
15 }catch(Exception e){<!-- -->
16 e.printStackTrace();
17 System.out.println("Server startup failed...");
18}
19}
20}
Create client
1public class BasicSocketClient {<!-- -->
2 public static void main(String[] args) {<!-- -->
3 //Create Socket object
4 try(Socket socket =new Socket("127.0.01",8888);
5 //Create an output stream object to send messages to the server.
6 PrintWriter pw = new PrintWriter(socket.getOutputStream())){<!-- -->
7 pw.println("Hello, server!");
8 pw.flush();
9 }catch(Exception e){<!-- -->
10 e.printStackTrace();
11 }
12}
13}
14

TCP one-way communication

One-way communication means that among the two communicating parties, one party is fixed as the sender and the other party is fixed as the receiver.

Create server
1public class OneWaySocketServer {<!-- -->
2 public static void main(String[] args) {<!-- -->
3 System.out.println("The server starts and starts monitoring...");
4 try(ServerSocket serverSocket = new ServerSocket(8888);
5 //Listen to port 8888 and obtain the Socket object corresponding to the client
6 Socket socket = serverSocket.accept();
7 //Get the input stream object through the Socket object corresponding to the client
8 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
9 //Get the output stream object through the Socket object corresponding to the client
10 PrintWriter pw = new PrintWriter(socket.getOutputStream())){<!-- -->
11 System.out.println("Connection successful!");
12 while(true){<!-- -->
13 //Read the message sent by the client
14 String str = br.readLine();
15 System.out.println("Client said:" + str);
16 if("exit".equals(str)){<!-- -->
17 break;
18}
19 pw.println(str);
20 pw.flush();
twenty one       }
22 }catch(Exception e){<!-- -->
23 e.printStackTrace();
24 System.out.println("The server failed to start...");
25}
26}
27}
28

Create client
1public class OneWaySocketClient {<!-- -->
2 public static void main(String[] args) {<!-- -->
3 //Get the Socket object corresponding to the server
4 try(Socket socket = new Socket("127.0.0.1",8888);
5 //Create keyboard input object
6 Scanner scanner = new Scanner(System.in);
7 //Get the output stream object through the Socket object corresponding to the server
8 PrintWriter pw = new PrintWriter(socket.getOutputStream());
9 //Get the input stream object through the Socket object corresponding to the server
10 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))){<!-- -->
11

12 while(true){<!-- -->
13 //Get the message that needs to be sent to the server through keyboard input
14 String str = scanner.nextLine();
15
16 //Send message to server
17 pw.println(str);
18 pw.flush();
19

20 if("exit".equals(str)){<!-- -->
21 break;
twenty two         }
twenty three

24 //Read the message returned by the server
25 String serverInput = br.readLine();
26 System.out.println("Returned by the server:" + serverInput);
27

28 }
29 }catch(Exception e){<!-- -->
30 e.printStackTrace();
31}
32}
33}

TCP two-way communication

Two-way communication means that among the two communicating parties, either party can be the sender and either party can be the receiver.

Create server
1public class TwoWaySocketServer {<!-- -->
2 public static void main(String[] args) {<!-- -->
3 System.out.println("Server started! Listening to port 8888...");
4 try(ServerSocket serverSocket = new ServerSocket(8888);
5 Socket socket = serverSocket.accept();
6 //Create keyboard input object
7 Scanner scanner = new Scanner(System.in);
8 //Get the input stream object through the Socket object corresponding to the client
9 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
10 //Get the output stream object through the Socket object corresponding to the client
11 PrintWriter pw = new PrintWriter(socket.getOutputStream());){<!-- -->
12
13 while(true){<!-- -->
14 //Read the message sent by the client
15 String str = br.readLine();
16 System.out.println("Client said:" + str);
17 String keyInput = scanner.nextLine();
18 //Send to client
19 pw.println(keyInput);
20 pw.flush();
twenty one       }
22 }catch(Exception e){<!-- -->
23 e.printStackTrace();
twenty four     }
25}
26}
Create client
public class TwoWaySocketClient {<!-- -->
  public static void main(String[] args) {<!-- -->
    try(Socket socket = new Socket("127.0.0.1", 8888);
      //Create keyboard input object
      Scanner scanner = new Scanner(System.in);
      //Get the input stream object through the Socket object corresponding to the server
      BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      //Get the output stream object through the Socket object corresponding to the server
      PrintWriter pw = new PrintWriter(socket.getOutputStream());){<!-- -->


      while (true) {<!-- -->
        String keyInput = scanner.nextLine();
        pw.println(keyInput);
        pw.flush();
        String input = br.readLine();
        System.out.println("The server said:" + input);
       }
     } catch (Exception e) {<!-- -->
      e.printStackTrace();
     }
   }
}