TCP network programming

Posted by marian on Thu, 24 Feb 2022 15:10:23 +0100

1, Basic concepts of network programming

1. What is computer network
Computers distributed in different regions are interconnected by communication lines through network devices such as hardware
Computer network, can be very convenient for information transmission, resource sharing!


2. What is the IP address of the computer
IP address is the unique identification of the computer in the Internet Just like the ID number of people in the society.
Native IP:
127.0.0.1
localhost


3. What is the domain name of the website in the network
Domain name can be simply understood as the alias of ip address It is more convenient to remember. After entering the domain name (e.g. www.baidu.com), the computer will visit the domain name resolver, get the ip address, and then visit


4. What is the port number of the computer
The range of port number is 0-65535*****
Similar to IP address, IP address is the unique identification of computer in the network
The port number is the identification of the program in the computer It is used to distinguish different applications in one computer
When using the port number, try to avoid the port number between 0-1024, because it has been occupied by some well-known software and windows operating system


5. What is the communication protocol between computers
It is the standard of communication between computers
It is a set of standards for data transmission rate, incoming interface, step control, error control and so on!
Common communication protocols:
1. http protocol: hypertext transfer protocol 80 port number
2. https protocol: Secure Hypertext Transfer Protocol 443 port number
3. ftp protocol: File Transfer Protocol 21 port number
4. TCP protocol: Transmission Control Protocol
5. UDP protocol: datagram protocol

6. Classification of network programming program:

1.B/S program: browser and server program
2.C/S program: client and server program

7.TCP protocol - OSI network model

It refers to the process of sending data from the software of one computer to the software of another computer
Seven layer network model: application layer / presentation layer / session layer / transport layer / network layer / data link layer / physical layer


Three handshakes and four waves

First handshake: the client sends a connection request to the server and waits for the server to confirm.

The client receives a handshake request and sends back a response to the server for the second time.

The third Handshake: the client sends confirmation information to the server again to confirm the connection.

First wave: the client sends a disconnect request to the server.

The second wave: after receiving the request, the server returns a reply to the client, and then the server enters the waiting shutdown state, and TCP is in the semi shutdown state.

The third wave: the server also plans to disconnect and send messages to the client.

The fourth wave: after receiving the message, the client replies with a response. Both sides closed.

2, TCP program

Two classes are needed to write the cs program of TCP

1. ServerSocket build server

2. Socket build client

ServerSocket is used to build a server. After the server is built, 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 Socket object to communicate with the client.

Socket is the endpoint of communication between two computers. One side holds a socket object to communicate. Socket functions like a telephone.

Now let's demonstrate the whole process of connecting the server and the client. Note: two classes are used to communicate, one to build the server and the other to build the client.

The first step is to build the server: the starting port number is 10086

ServerSocket server = new ServerSocket(10086); //Build server

Step 2: use accept to receive the connection of the client, and name the linked port socket

Socket socket = server.accept(); //Wait for the client to connect. The connected endpoint is socket

Step 3: create a client:

Socket socket = new Socket("127.0.0.1",10086);

The parameters in the port are IP address and port number. The local IP address is 127.0.0.1 or localhost. The port number is the port number of the server.

Run the two classes in this way, and our server and client will be connected successfully.

Now let's make some simple communication. socket is used for communication. Use input and output streams for communication.

Send a message to the server:

//Send a message
        OutputStream os = socket.getOutputStream(); //Endpoint call output stream
        PrintStream ps = new PrintStream(os);//Convert output stream to print stream
        ps.println("Welcome to this server!");

Message received by client:

InputStreamReader converts a byte stream into a character stream, and BufferedReader caches characters from the character stream.

InputStream is = socket.getInputStream(); //Calling an input stream with an endpoint
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String text = br.readLine();
        System.out.printf("The message received by the client is:"+text);

The methods of sending messages from the client and receiving messages from the server are the same as above.

Note: it must be sent at one end and received at the other end. It cannot be sent at both ends at the same time.

The overall code is as follows: code example:

Server side:

public class Demo1 {
    public static void main(String[] args) throws IOException {
       ServerSocket server = new ServerSocket(10086); //Build server
        System.out.println("The server is set up!");
        Socket socket = server.accept(); //Wait for the client to connect. The connected endpoint is socket
        System.out.println("A client has successfully connected√");
        //Send a message
        OutputStream os = socket.getOutputStream(); //Endpoint call output stream
        PrintStream ps = new PrintStream(os);//Convert output stream to print stream
        ps.println("Welcome to this server!");
        //receive messages
        InputStream is = socket.getInputStream(); //Receive stream with port
        /**
         * InputStreamReader Convert byte stream to character stream
         * BufferedReader Cache characters from character stream
         */
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String text = br.readLine();
        System.out.printf("The server received a reply from the client:"+text);
        System.out.printf("End of server program execution!");
    }
}

client:

public class Demo2 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",10086);
        InputStream is = socket.getInputStream(); //Calling an input stream with an endpoint
        /**
         * InputStreamReader Convert byte stream to character stream
         * BufferedReader Cache characters from character stream
         */
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String text = br.readLine();
        System.out.printf("The message received by the client is:"+text);
        OutputStream os = socket.getOutputStream();
        PrintStream ps = new PrintStream(os);
        ps.println("Hello, server!");
    }
}

Operation results:

After executing the server, the server waits for the client to connect.  

Rerun client: client code results

Server side result: the whole is over.

III. adding multithreading to the server

In the above method, one server can connect multiple clients, but it can only be executed in sequence. After processing the first client, we can process the second client. The efficiency is too low, and the server cannot handle only one client at a time. So we need to add multithreading technology. Multi threaded technology connection:

https://mp.csdn.net/mp_blog/creation/editor/121070409https://mp.csdn.net/mp_blog/creation/editor/121070409

Loop the receiving client, and add multithreading after the receiving client. Each time a client is received, it enters a new thread. Each thread completes the work of each thread.  

Please read the source code:

public class Demo3 {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(20086);
        while(true){
           Socket socket = server.accept();
           new Thread(){
               @Override
               public void run() {
                   try {
                       InputStream is = socket.getInputStream();
                       BufferedReader br = new BufferedReader(new InputStreamReader(is));
                       System.out.println(Thread.currentThread().getName());
                       System.out.println("Message from client:"+br.readLine());
                       OutputStream os = socket.getOutputStream();
                       PrintStream ps = new PrintStream(os);
                       ps.println("I'm the server, thanks for the link");
                       Thread.sleep(10000);   //Sleep for ten seconds
                       System.out.println(Thread.currentThread().getName()+"Sleep over!");
                   } catch (IOException e) {
                       e.printStackTrace();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }.start();
        }
    }
}

So we keep connecting at the client.

The running results are as follows: multiple threads run together. A server connects multiple clients and processes them at the same time.

 

 

So far in this paper, all the methods of TCP network programming have been introduced.

The author's code is not easy. Your praise collection is my encouragement~

Topics: network p2p TCP/IP