In a recent project that was about to end, Socket programming was used to call another system for processing and returning data. So summarize the basic knowledge of Socket again.

1. TCP/IP protocol

Since network programming involves the interaction between several systems, the first thing to consider is how to accurately locate one or several hosts on the network, and how to carry out reliable and efficient data transmission. This is where TCP/IP is used. TCP/IP (Transmission Control Protocol) consists of IP at the network layer and TCP at the transport layer. The IP layer is responsible for the location of network hosts and routing of data transmission. A host on the Internet can be uniquely determined by IP address. The TCP layer is responsible for the application-oriented reliable or unreliable data transfer mechanism, which is the primary object of network programming.

2. TCP and UDP

TCP is a connection-oriented protocol that guarantees reliable transmission. Through TCP protocol transmission, the obtained is a sequential error-free data flow. A connection must be established between two pairs of sockets on the sender and receiver to communicate over TCP. When one socket (usually a server socket) is waiting for a connection to be established, the other socket can request a connection. Once the two sockets are connected, They can be two-way data transmission, both can send or receive operations. UDP is a connectionless protocol. Each datagram is an independent message, including a complete source address or destination address. It is transmitted to the destination in any possible path on the network. TCP and UDP: TCP features:

  1. TCP is a connection-oriented protocol. It establishes a connection through a three-way handshake and disconnects the connection when the communication is complete. As a connection-oriented protocol, TCP can only be used for point-to-point communication. It also takes time and expense to set up a connection.
  2. TCP transfers large data without size limitation.
  3. TCP is a reliable protocol that ensures that the receiver can receive all data sent by the sender completely and correctly.

UDP features: 4. UDP is connectionless communication protocol. UDP data includes destination port number and source port number information. 5. UDP data transmission has a size limit. Each transmitted datagram must be within 64KB. 6. UDP is an unreliable protocol. Datagrams sent by the sender do not always arrive at the receiver in the same order. TCP and UDP application: 7. TCP has a strong vitality in network communication, such as remote connection (Telnet) and file transfer (FTP) require data of variable length to be transmitted reliably. But reliable transmission is to pay a price, the correctness of the data content of the test must occupy the computer processing time and network bandwidth, so TCP transmission efficiency is not as high as UDP. 8. UDP is easy to operate and requires less monitoring, so it is usually used for client/server applications in decentralized systems with high LAN reliability. For example, the video conference system does not require the absolute accuracy of audio and video data, as long as the consistency can be guaranteed. In this case, UDP is obviously more reasonable.

What is a Socket

A Socket, also known as a Socket, is used to describe an IP address or port and is a handle to a communication chain. Two programs on the network through a two-way communication connection to achieve data exchange, one end of the two-way link is called a Socket, a Socket by an IP address and a port number uniquely determined. Applications typically make or respond to network requests through “sockets”. Socket is a very popular programming interface of TCP/IP protocol. However, the protocol types supported by Socket are not only TCP/IP, so there is no necessary connection between the two. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol. Socket communication process: the server monitors whether a port has a connection request, the client sends a connection request to the server, the server receives the connection request to the client sends a receiving message, so a connection is established. Both clients and servers can send messages to each other to communicate with each other. The basic working process of a Socket consists of the following four steps: Creating a Socket; Open the I/O stream connected to the Socket. Read and write sockets according to certain protocols; Close the Socket.

4. Sockets in Java have two classes under the Java.net package: Socket and ServerSocket. ServerSocket is used on the server. The Socket is used to establish network connections. When the connection is successful, both ends of the application program will generate a Socket instance, and operate the instance to complete the required session. Sockets are equal to each other for a network connection, there is no difference between levels on the server side and on the client side. Both sockets and ServerSockets do their work through the SocketImpl class and its subclasses. List a few common constructors:

9 Socket(InetAddress address, int port); // Create a stream Socket and connect it to the specified port number of the specified IP address Socket(String host, int port); // Create a stream Socket and connect it to the specified port on the specified host Socket(InetAddress address, int port, InetAddress localAddr, int localPort); // Create a Socket and connect it to the specified remote port on the specified remote address Socket(String host, int port, InetAddress localAddr, int localPort); // Create a Socket and connect it to the Socket of the specified remote port on the specified remote host (SocketImpl impl); // Create an unconnected Socket with the SocketImpl specified by the user

ServerSocket(int port); ServerSocket(int port, int backlog); ServerSocket(int port, int Backlog, InetAddress bindAddr); // Create the server constructor with the specified port, listening backlog, and local IP address to bind to. Address, host, and port are the IP address, hostname, and port number of the other party in the two-way connection, respectively. Stream specifies whether a socket is a stream socket or a datagram socket, localPort specifies the port number of the local host, localAddr and bindAddr are the addresses of the local machine (ServerSocket’s host address), impl is the socket’s parent class, It can be used to create both serverSockets and sockets. Count indicates the maximum number of connections supported by the server. Note: The port number must be chosen carefully. Each port provides a specific service, and the corresponding service can only be obtained if the correct port is given. Ports from 0 to 1023 are reserved for the system. For example, the HTTP service port number is 80, the Telnet service port number is 21, and the FTP service port number is 23. Therefore, you are advised to select a port number greater than 1023 to prevent conflicts. Several important Socke methods:

3 public InputStream getInputStream(); Public OutputStream getOutputStream(); public OutputStream getOutputStream(); // The other end of the method connection will get input and return an OutputStream object instance public Socket Accept (); // Used to “block” until a connection is received and an instance of the client Socket object is returned. “Blocking” is a term that causes a program to run temporarily to “stay” in place until a session is created, and then the program continues; Usually “blocking” is caused by loops. Note: Both the getInputStream and getOutputStream methods generate an IOException, which must be caught because the stream object they return is usually used by another stream object.

4. Basic Client/Server programs

Here is a basic client/server program code. The main realization of the server has been listening to a port, waiting for the client connection request. The client connects to the server based on the IP address and port number, enters a line of information on the keyboard, and sends the information to the server. Then the client receives the information from the server, and finally terminates the session. This program can only accept one client connection at a time. The BufferedReader’s readLine() method did not get a newline, so the BufferedReader’s readLine() method did not get a newline. The BufferedReader’s readLine() method did not get a newline. I am dizzy ~~@_@ client:

package demo4;

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

public class SocketClient {
    public static void main(String[] args) {

        try {
            Create a Socket * / / * *
            // Create a stream socket and connect it to the specified port at the specified IP address.
            Socket socket = new Socket("127.0.0.1".2013);// Socket client

            / / 60 s timeout
            socket.setSoTimeout(60000);

            /** Sends the message that the client is ready to transmit */

            // Outputs the string read from the input to the Server
            BufferedReader sysBuff = new BufferedReader(new InputStreamReader(System.in));

            // Get the output stream from the Socket object and construct the PrintWriter object
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);

            printWriter.println(sysBuff.readLine());    // Just say one word

            // Refresh the output stream so that the Server receives the string immediately
            printWriter.flush();

            /** Is used to get information from the server */
            // Get the input stream from the Socket object and construct the corresponding BufferedReader object
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // Input reads a string
            String result = bufferedReader.readLine();
            System.out.println("Server say : " + result);

            Close the Socket * / / * *
            printWriter.close();
            bufferedReader.close();
            socket.close();
        } catch (Exception e) {
            System.out.println("Exception:"+ e); }}}Copy the code

Server:

package demo4;

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

public class SocketServer {
    public static void main(String[] args) {
        try {
            Create ServerSocket * / / * *
            // Create a ServerSocket on port 2013 to listen for client requests
            ServerSocket serverSocket = new ServerSocket(2013);

            while (true) {
                // Listen for and accept connections to the Socket. When the request arrives, a Socket object is generated and execution continues
                Socket socket = serverSocket.accept();

                /** Get the message from the client */
                // Get the input stream from the Socket object and construct the corresponding BufferedReader object
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // Gets the string read in from the client
                String result = bufferedReader.readLine();
                System.out.println("Client say : " + result);

                /** Sends the */ that the server is ready to transmit
                // Get the output stream from the Socket object and construct the PrintWriter object
                PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                printWriter.print("hello Client, I am Server!");
                printWriter.flush();

                Close the Socket * / / * *printWriter.close(); bufferedReader.close(); socket.close(); }}catch (Exception e) {
            System.out.println("Exception:" + e);
        }finally{
// serverSocket.close();}}}Copy the code

5. Multiple clients connect to the server

The above server-side program can only connect to one client at a time, which is obviously impossible in practice. The usual network environment is a number of clients connected to a host for communication, so we want to reform the above procedures. Design idea: the server-side main program listens for a certain port, the client initiates the connection request, the server-side main program receives the request, and constructs a thread class, which is used to take over the session. When a Socket session is created, the session is handed over to the thread for processing, and the main program continues to listen. The following implementation process is as follows: the client establishes a connection with the server, the client sends a message, and the server processes and returns a message according to the message. If the client applies for closing, the server closes the connection and the communication between the two sides ends.

package demo228;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: From south to north *@Date: 02/28/2022 / hast judged *@Description: * /
import java.io.*;
import java.net.*;

public class Server extends ServerSocket {
    private static final int SERVER_PORT = 2013;

    public Server(a) throws IOException {
        super(SERVER_PORT);     // call the constructor of the parent class
        try {
            while (true) {
                Socket socket = accept();   // Call the parent constructor directly
 				 // Receives the request socket and creates a new conversation thread for it
                new CreateServerThread(socket);// When there is a request, start a thread to process it}}catch (IOException e) {
        } finally{ close(); }}/ / thread class
    class CreateServerThread extends Thread {
        private Socket client;
        private BufferedReader bufferedReader;
        private PrintWriter printWriter;

        public CreateServerThread(Socket s) throws IOException {
            client = s;
            bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            printWriter = new PrintWriter(client.getOutputStream(), true);
            System.out.println("Client(" + getName() + ") come in...");
            start();
        }

        public void run(a) {
            try {
                String line = bufferedReader.readLine();

                while(! line.equals("bye")) {
                    printWriter.println("continue, Client(" + getName() + ")!");
                    line = bufferedReader.readLine();
                    System.out.println("Client(" + getName() + ") say: " + line);
                }

                printWriter.println("bye, Client(" + getName() + ")!");
                System.out.println("Client(" + getName() + ") exit!");
                printWriter.close();
                bufferedReader.close();
                client.close();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) throws IOException {
        newServer(); }}Copy the code

The client

package demo228;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1".2013);
            socket.setSoTimeout(60000);

            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String result = "";

            while(result.indexOf("bye") = = -1){

                BufferedReader sysBuff = new BufferedReader(new InputStreamReader(System.in));
                printWriter.println(sysBuff.readLine());

                printWriter.flush();

                result = bufferedReader.readLine();
                System.out.println("Server say : " + result);
            }

            printWriter.close();
            bufferedReader.close();
            socket.close();
        } catch (Exception e) {
            System.out.println("Exception:"+ e); }}}Copy the code

  

6. Information sharing

The above allows for multiple client and server connections, but messages are still propagated between one client and one server. Now we want to implement information sharing, that is, clients can also send messages to other clients, and the server receives messages from clients and broadcasts them to other clients. Similar to a chat room, information can be shared between multiple clients. Design idea: the client loop can continuously input to send messages to the server, and start a thread, specially used to listen to the message sent from the server and print out. When the server side starts, it starts a thread that listens for when messages need to be sent to the client. Each time a client connection request is accepted, a thread is started for processing and the client information is stored in a common collection. When the client sends a message, the server queues the message sequentially, and when output is needed, it takes the broadcast from the queue to each client. Start the server and client program (can start more than one client), the client first input any content enter to establish a connection with the server, and then enter the login user name as prompted, and then you can chat with the input user name identity. On the client, run the showuser command to view the list of online users, and enter bye to apply for disconnecting from the server. PS: The following code has found a small problem with Chinese garbled characters. When the file is set to UTF-8 encoding, no matter how to set the input stream encoding in the code, it will still be garbled characters. After the file is set to GBK encoding, the input stream encoding can be displayed normally without setting in the code.

7. File transfer

The client sends the file to the server, and the server can obtain the file name for saving, obtain the file size to calculate the transmission progress. It is relatively simple, and directly paste the code.