Network programming based on TCP

Posted by tidou on Thu, 25 Nov 2021 00:05:41 +0100

C/S program of TCP protocol

Two classes need to be used to write CS programs of TCP protocol:

  1. ServerSocker build server
  2. Socker build client

During network construction, there must be a server first, and then we can build a client connection server.

Two classes are described below:

ServerSocker

It is used to create a server. After creation, a port number will be bound;

The server can then wait for the client to connect.

Every time a client is connected, the server will get a new Socker object to communicate with the client.

Common construction methods:

ServerSocker(int port);

Create a server based on TCP/IP protocol and bind the specified port number.

Note: the range of parameter port is 0-65535 (the first 1024 parameters have been bound by the software commonly used by the client)

Common methods:

Socket accept();
    Waiting for client connection
    This method causes the thread to block
    Until a new client is successfully connected, return Socket Object before the thread continues execution.
void close();
	Start waving four times;
	Release the occupied port number and shut down the server.

Socker

Socker, called socket, refers to the endpoint of computer communication. Computers communicate with each other through socket.

Construction method

Socket(String ip, int port)
    Create a socket and connect to the specified ip And port number of the server.
    Parameter 1. Server ip address
    Parameter 2. Port number of the server software

Common methods:

  • OutputStream getOutputStream( ); If you want to send a message, send it with Output;
  • InputStream getInputStream( ) ; If you want to receive messages, use Input;
  • void close( ); If not, use this method to close the socket;

Note that one of the two sides must be sending and the other receiving; The server / client outputs / inputs first, and the client / server inputs / outputs first.

give an example

public class Demo {
    /**
     * TCP Network programming of protocol
     * Server side
     */
    public static void main(String[] args) throws IOException {
        //Build server
        ServerSocket server = new ServerSocket(55565);
        System.out.println("The server started successfully");
        //Waiting for client connection
        Socket socket = server.accept();
        System.out.println("A client connection succeeded");

        //Send a message
        OutputStream os = socket.getOutputStream();
        PrintStream ps = new PrintStream(os);
        ps.println("Welcome to the server");
        //Receive message
        System.out.println("-------Dividing line-------");
        InputStream is = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String text = br.readLine();
        System.out.println(text);
        System.out.println("Client message received");
    }
}
public class ClientDemo {
    /**
     * TCP Network programming of protocol
     * client
     */
    public static void main(String[] args) throws IOException {
        //Build client
        Socket socket = new Socket("127.0.0.1", 55565);

        //Receive message
        InputStream is = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String text = br.readLine();
        System.out.println(text);
        //Reply message
        System.out.println("-------Dividing line-------");
        OutputStream os = socket.getOutputStream();
        PrintStream ps = new PrintStream(os);
        ps.println("I have received the message");
        System.out.println("Message sent to server");
    }
}

result:

  • Server side:

The server started successfully

A client connection succeeded

--------Dividing line--------

I have received the message
Client message received

  • client:

Welcome to the server

-------Dividing line-------

Message sent to server

Multithreaded server

The above knowledge points only realize the communication between a server and a client, but how to make a server communicate with multiple clients?

Based on the above example, see the following modifications:

//Build server
ServerSocket server = new ServerSocket(55565);
System.out.println("The server started successfully");
//Waiting for client connection
while(true){
    Socket socket = server.accept();
	System.out.println("A client connection succeeded");
}

accept() is to wait for the client to connect. When a client connects successfully, it will recycle the next connection. Because it is an endless loop, it can always connect to a new client;

However, there will be a problem. During the process of connecting to a client and interacting, the loop will remain stuck here until the interaction is completed. This leads to a problem: the server cannot connect with other clients during client interaction.

How can this be solved? Using multithreading technology:

That is, connect a client to create a thread, and then the server interacts with the client through this thread.

//Build server
ServerSocket server = new ServerSocket(55565);
System.out.println("The server started successfully");
//Waiting for client connection
while(true){
    Socket socket = server.accept();
	System.out.println("A client connection succeeded");
    new Thread(){
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
    }.start();
}

Topics: Java Algorithm data structure