Implementation of TCP communication in Java

0, TCP communication

Transmission Control Protocol ( TCP , Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based transport layer communication protocol.

If you use the WireShark tool, you can see the entire process of establishing a TCP connection.

1. One-way communication

In one-way communication, one party is fixed as the sender of information, and the other party is fixed as the receiver of information.

1.1 Server in one-way communication

The server is the receiver of the information.

Use the ServerSocket class to create a server and set the service port to 9527;

The serverSocket.accept() method is used to monitor the connection to port 9527. This method is a blocking method. When the data is received, the program will continue to execute, otherwise it will always be in a waiting state;

After receiving the data, because it uses byte stream transmission, the conversion stream using InputStreamReader is used to convert the byte data into a string, and BufferedReader is used for reading and output;

When the server receives the client's request, it needs to send response data to the client, use PrintWriter to send the response message, and need to use the flush() method to send the message;

When the message sent by the client is "goodbye", the server exits the communication and closes the service.

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        System.out.println("服务器启动!");
        try {
            ServerSocket serverSocket = new ServerSocket(9527);
            Socket socket = serverSocket.accept();
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            System.out.println("接收客户端消息");

            while (true){
                String in = br.readLine();
                System.out.println("接收到客户端发来的请求:" + in);
                if("再见".equals(in)){
                    break;
                }
                pw.print(in + "回报");
                pw.flush();
            }
        } catch (IOException e) {
            System.out.println("服务启动失败!");
            e.printStackTrace();
        }
    }
}

After starting, the server output is:

Server starts!

1.2 Client in one-way communication

The client is the sender of the information.

  • Create a Socket object ​Socket("localhost", 9527)​and establish communication with the service with port 9527;
  • The method of receiving and sending messages is the same as that of the server;
  • In order to be able to send messages to the server in a loop, an infinite loop is used. When the user enters "goodbye", the loop is terminated;
  • Use a Scanner object to receive keyboard input.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 9527);
            //读取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //获取输出流
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            //从键盘获取输入
            Scanner scanner = new Scanner(System.in);

            while (true){
                //从控制台获取向服务端发送的消息
                String next = scanner.next();
                pw.println(next);
                pw.flush();

                String s = br.readLine();
                System.out.println("收到服务器响应:" + s);

                if("再见".equals(next)){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.3 Kenritsu Tsushin

After starting the client, enter "Hello" in the client's console and observe the consoles of the server and client.

Enter "Bye" in the client's console and observe the server and client consoles

2. Two-way communication

In two-way communication, both parties can be both the sender and the receiver of information.

2.1 Server in two-way communication

Set up sending and receiving messages on the server side.

Scanner is also used on the server side to receive console input and send it to the client.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static void main(String[] args) {
        try{
            ServerSocket serverSocket = new ServerSocket(9528);
            Socket socket = serverSocket.accept();
            //获取客户端请求
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //获取键盘输入
            Scanner scanner = new Scanner(System.in);
            //发送消息到客户端
            PrintWriter pw = new PrintWriter(socket.getOutputStream());

            while (true){
                String input = br.readLine();
                System.out.println("收到客户端请求: " + input);
                String output = scanner.nextLine();

                pw.println(output);
                pw.flush();

                if("再见".equals(input)){
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("服务启动失败!");
        }
    }
}

2.2 Client in two-way communication

Set up sending and receiving messages on the client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        try{
            Socket socket = new Socket("127.0.0.1", 9528);
            //获取服务端响应
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //获取客户端用户输入
            Scanner scanner = new Scanner(System.in);
            //向服务端发送请求
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            System.out.println("准备接收请求……");
            while (true){
                String output = scanner.next();
                pw.println(output);
                pw.flush();

                String input = br.readLine();
                System.out.println("来自服务端的响应: " + input);
                if("再见".equals(output)){
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

2.3 Suggested communications

Start the server and client, and enter the content in the console:

Problems:

Such communication requires the client to send a message once and the server to reply once. If the client sends two messages at the same time, the messages will be out of sync.

For example, the following situation:

You can think about this problem first and how it should be solved. The solution will be given later.

Guess you like

Origin blog.csdn.net/QQ156881887/article/details/130351379