java socket for communication programming

Recently, I'm thinking about the implementation principle of some software and studying how those popular software are developed. It's quite interesting. Reviewing the software used every day, I found that the most commonly used software should be communication software, such as wechat and nailing. So I wondered how these communication software were developed and what technologies were used? At ordinary times, most of the work of developing software is CRUD. There is little research on some underlying technologies in some fields that are not your own work, so you can also do some research on some underlying technologies and software you are interested in in in your spare time. This article is a preliminary study of communication software.

The development technology of Java Communication software starts from socket. Here are some basic understanding and practice of socket technology.

Let's take a look at the actual effect picture:

 

1, What is socket?

In network communication, we have all heard of TCP/UDP and HTTP. What is socket? Socket is an intermediate software abstraction layer for the communication between application layer and TCP/IP protocol family. It is a group of interfaces. In the design mode, socket is actually a facade mode. It hides the complex TCP/IP protocol family behind the socket interface. For users, a set of simple interfaces is all, allowing the socket to organize data to comply with the specified protocol. Generally, it can be used for communication software development, RPC Protocol Development, file transfer development, etc. In use, sockets are mainly divided into ServerSocket and socket. ServerSocket class represents socket server and socket class represents socket client.

2, socket interaction process

What is the use process of socket?

The interaction process between the two is as follows:
1. Create a ServerSocket on the server side, call the accept() method and wait for the client to connect.
2. The client program creates a Socket and requests to establish a connection with the server.
3. The server receives the connection request from the customer and creates a new Socket to establish a connection with the customer. The server continues to wait for the new request.

4. Use network I/O to operate the sending and receiving of messages. For example, BufferedReader reads / BufferedWriter writes.

The following is the interaction diagram between the client and server of socket.

 

3, Actual combat drill

After knowing the knowledge of socket, let's do some practical exercises. The communication implementation of socket is divided into two applications: server and client. At the deployment level, there are two independent applications. We first implement the code of the server, as follows:

package socketStudy;

import java.io.*;
import java.net.*;

/**
 * socket Server
 * @author xiaoming
 * @version 1.0
 * @date 2022-01-28
 */
public class CommunicationServer {

    public static String socketserver_ip = "127.0.0.1";
    public static int socketserver_port = 8881;

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(socketserver_port);
            System.out.println("CommunicationServer Start server....Port is:"+socketserver_port+" wait connect...");
            Socket s = ss.accept();
            System.out.println("Client connection received, client:"+s.getInetAddress().getHostAddress()+"Connected to server");

            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //Read the message sent by the client
            String mess = br.readLine();
            System.out.println("[[received client information] the information is:"+mess);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bw.write("[Server] has received the message sent by the client. The message is:"+mess+"\n");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

First, start the socket program of the server, and create a socket server for the client by initializing the ServerSocket(int port) instance. Port is the port number provided by the server, and the service IP address provided externally is the IP address of the local machine. Here, the local connection (127.0.0.1) is adopted. Then through ServerSocket The accept () method monitors the connection of the client, and then uses BufferedReader and BufferedWriter to send and receive messages.

Let's look at the client code of socket:

package socketStudy;

import java.io.*;
import java.net.*;

/**
 * socket client
 * @author xiaoming
 * @version 1.0
 * @date 2022-01-28
 */
public class CommunicationClient {
    public static void main(String[] args) {
        try {
            //Connect socket server
            Socket s = new Socket(CommunicationServer.socketserver_ip,CommunicationServer.socketserver_port);

            //Build IO
            InputStream inp = s.getInputStream();//Input stream, received information
            OutputStream outp = s.getOutputStream();//Output stream, outgoing message

            //Send a message to the server
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outp));
            bw.write("Test the communication between the client and the server, and the server returns the message to the client\n");
            bw.flush();

            //Read the message returned by the server
            BufferedReader br = new BufferedReader(new InputStreamReader(inp));
            String mess = br.readLine();
            System.out.println("[[received server information]:"+mess);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The client first uses new Socket(String ip,int port) to connect the ip and port number of the server. Then use BufferedReader and BufferedWriter to send and receive messages. Start communication server first Java. After successful startup, wait for the connection, and you will see the log:

"C:\Program Files\Java\jdk1.8.0_311\bin\java.exe" ...
CommunicationServer Start server....Port is:8881 wait connect...

At this time, the server does not have any client connection. Start the client program and run communicationclient Java. After successful startup, you will see that the server log is updated as follows:

"C:\Program Files\Java\jdk1.8.0_311\bin\java.exe" ...
CommunicationServer Start server....Port is:8881 wait connect...
Client connection received, client:127.0.0.1 Connected to server
[Receive client information] the information is: test the communication between the client and the server, and the server returns the message to the client

At the same time, the server log is displayed as:

"C:\Program Files\Java\jdk1.8.0_311\bin\java.exe" ...
[[receive server information]: the [server] has received the message sent by the client. The message is: test the communication between the client and the server, and the server returns the message to the client

In this way, the communication between server and client programs of a complete socket is completed.

4, Summary of learned knowledge and problems

1. Learned knowledge

Learned the principle and preliminary usage of socket, as well as the error prone points and correction methods in practice.

Thinking: how to achieve continuous messaging and communication between multiple clients?

2. Problems encountered

(1) Conflict of class names

I created a new socket server class called ServerSocket. As a result, it conflicts with the socket server implementation class. It's embarrassing...

(2) The processing of sending and receiving messages is reversed, which is easy to be confused.

A good way is to write the parameter definition clearly and add comments.

InputStream receivemsginuts / / input stream, the information received
OutputStream sendMsgOutS / / output stream, messages sent

(3) . the sending and receiving process of program operation is chaotic

Because it is a server-side client mode, it will send and receive messages back and forth. If the printed log is not clear, it is easy to get confused about the process of sending and receiving messages. Many examples on the Internet can be realized, but exploring the process is still easy to be confused for beginners. It is recommended to print the Key log at the entrance and end of each program. The role of the processor, the things handled and the returned results are added to the log, which is of great benefit to learning and troubleshooting.

Keywords: Java network socket Back-end

Added by rodrigocaldeira on Sun, 30 Jan 2022 10:02:40 +0200