Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Read about WebSocket recently, and note the simple use of SpringBoot and WebSocket

1 the WebSocket birth

Classic question: why do you need WebSocket when you have HTTP?

Because the HTTP protocol requires the client to initiate a request to the server, the server can respond to the data, and the server cannot actively communicate with the client. In some scenarios, the server is required to initiate communication and push data to the client, so the WebSocket protocol is born.

2 Introduction to WebSocket

WebSocket protocol was born in 2008 and became an international standard in 2011. WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

Its main features are: allow the server to actively send information to the client.

Usage Scenarios:

  • The chat room
  • Being pushed

3 WebSocket usage

1 Prepare a SpringBoot environment

2 Add the WebSocket configuration

@Configuration
public class websocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(a) {
        return newServerEndpointExporter(); }}Copy the code

3 Add the server WebSocket class

@Component
@Slf4j
@ServerEndpoint(value = "/test/{userId}")
public class SocketTest {
    
    private String userId;

    // execute on connection
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
        this.userId = userId;
        log.info("New connection: {}", userId);
    }

    // Execute when closed
    @OnClose
    public void onClose(a) {
        log.info("Connection: {} closed".this.userId);
    }

    // Execute when a message is received
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("Received message {} from user {}".this.userId, message);
        session.getBasicRemote().sendText("Receive" + this.userId + "The news"); // Reply to the user
    }

    // Execute when connection error occurs
    @OnError
    public void onError(Session session, Throwable error) {
        log.info(Error sending connection for user userId: {}.this.userId); error.printStackTrace(); }}Copy the code

4. Start the project and use online tools to imitate the front-end to call WebSocket

Online tools: coolaf.com/tool/chatte…

5 Viewing Data

Take local as an example:

Access: the ws: / / localhost: 8080 / test/user001

// Enter the address, click Connect, and see the console output new connection
// Send the ha to the background, see the console received the user ha
// Disconnect, see the console, disconnect

// New connection: user001
// Received a message from user user001
// Connection: user001 closed
Copy the code

References:

www.ruanyifeng.com/blog/2017/0…