Two ways SpringBoot integrates WebSocket

In April 2014, this site had comprehensively studied HTML5 technology, and featured the HTML5 WebSocket example. The API in the Servlet3.0 specification used at that time required the support of Tomcat7 (it seems that WebSocket was also added in the later maintenance version of Tomcat6. support), as early as at the beginning, this example was still a special function of this site, and many people came to me to ask for the source code. After many years, I used the SpringBoot architecture to experience the implementation of integrated WebSocket. After some information, I probably found two ways of implementation. I practiced them separately, so I call these two ways JDK built-in version And Spring package version.

1. JDK built-in version

Mainly use the annotations under the javax.websocket package for integration, mainly including: ServerEndpoint, OnOpen, OnMessage, OnClose, OnError related classes and annotations to integrate, overall relatively simple, all are declared based on the methods defined by annotations, refer to As shown in the following code:

JdkWebSocket

package cn.chendd.websocket.jdk;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * websocket实现
 *
 * @date 2023/6/2 21:02
 */
@Component
@ServerEndpoint(value = "/websocket/jdk")
public class JdkWebSocket {

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocketConfig.onOpen");
    }

    @OnMessage
    public void onMessage(Session session , String message) {
        System.out.println("WebSocketConfig.onMessage-->" + session + "--->" + message);
    }

    @OnClose
    public void onClose() {
        System.out.println("WebSocketConfig.onClose");
    }

    @OnError
    public void onError(Session sesison , Throwable throwable) {
        System.out.println("WebSocketConfig.onError-->" + sesison + "--->" + throwable);
    }

}

JdkWebSocketConfig

package cn.chendd.websocket.jdk;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author chendd
 * @date 2023/6/2 21:15
 */
@Configuration
public class JdkWebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

}

operation result

2. Spring package version

The Spring package version encapsulates the message type and provides a more comprehensive WebSocket API, which is worthy of in-depth analysis.

SpringWebSocketHandler

package cn.chendd.websocket.spring;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * SpringWebSocketHandler
 *
 * @author chendd
 * @date 2023/6/2 22:08
 */
@Component
public class SpringWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        System.out.println("SpringWebSocketHandler.afterConnectionEstablished");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
        System.out.println("SpringWebSocketHandler.handleMessage");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        System.out.println("SpringWebSocketHandler.handleTextMessage");
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
        System.out.println("SpringWebSocketHandler.handlePongMessage");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        System.out.println("SpringWebSocketHandler.handleTransportError");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        System.out.println("SpringWebSocketHandler.afterConnectionClosed");
    }

    @Override
    public boolean supportsPartialMessages() {
        System.out.println("SpringWebSocketHandler.supportsPartialMessages");
        return super.supportsPartialMessages();
    }
}

SpringWebSocketConfig

package cn.chendd.websocket.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import javax.annotation.Resource;

/**
 * SpringWebSocketConfig
 *
 * @author chendd
 * @date 2023/6/2 22:11
 */
@Configuration
@EnableWebSocket
public class SpringWebSocketConfig implements WebSocketConfigurer {

    @Resource
    private SpringWebSocketHandler springWebSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(springWebSocketHandler , "/websocket/spring").setAllowedOrigins("*");
    }
}

operation result

 

3. Other instructions

(1) This example focuses on the server-side Java code example. No front-end example is written. You can refer to the front-end HTML integration in the project source code below, or use the page address of the online WebSocket test used in this example for online verification , right-click to view its source code is also the relevant code of the native HTML5 specification;

(2) The built-in version of JDK and the packaged version of Spring are provided. I personally recommend using the packaged version of Spring. After all, the annotations of JDK are not clear enough to describe the specific parameters of the annotated method, and the packaged version of Spring has a message type. encapsulation;

(3) The code is relatively simple, combined with the full code in the previous " Guess the Mini Program You Choose " is also included, the code package structure is as follows:

(4) The complete source code is visible: the original text

Two ways SpringBoot integrates WebSocket Welcome to Chen Dongdong's personal experience sharing platform https://www.chendd.cn/blog/article/1667515782887432194.html

Guess you like

Origin blog.csdn.net/haiyangyiba/article/details/131147209