Personal Notes-SpringBoot Simple Integration of WebSocket

foreword

1. What is Socket?

Before understanding Socket, you first need to understand TCP/IP (Transmission Control Protocol/Internet Protocol) and UDP (User Datagram Protocol). The two are in a corresponding relationship.

Socket is the responsibility of an interface. Acts as an intermediary between user processes and TCP/IP. In other words, Socket can be understood as a TCP/IP interface service, and when connecting to it to transmit data, you only need to understand the interface. This is what is often said in programming languages: interface-oriented programming.

Extension: usage scenarios between Socket and Http.

1. First of all, Http is a simple object access protocol, which is often used for communication between B/S. It is mainly used for the application layer. For example, for common web pages, the user interface corresponds to the front end, and the data operation corresponds to the server end. The request can only be initiated by the front end, and the server passively receives the request and returns it after internal logic processing.

2. Socket is the encapsulation of TCP/IP protocol. Note : Socket itself is not a protocol. It is an API for calling

For example, a common manual customer service system. We can often see that in the manual customer service function of some APPs, users will input some keywords and send them to the server, and the server will return the answer that the user wants after data processing. If the HTTP protocol is used, each query of the user will generate a service connection. If the number of users is too large, the HTTP connections initiated will increase exponentially. The pressure on the server side is enormous. Using the Socket protocol can avoid multiple connections very well. When the user enters the chat interface for the first time, a long connection is made directly with the Socket service. If the user does not send a message for a long time, the link will be disconnected (you can set the waiting time for the message by yourself).

2. What is WebSocket?

1. Both the WebSocket and Socket protocols are based on the TCP protocol and are mainly used to realize full-duplex communication between B/S. It can better save server resources and bandwidth so as to achieve the purpose of real-time communication.

2. WebSocket is very similar to Socket. The former can open a certain URL address, so that a TCP-like connection can be established between the client and the server, so as to facilitate the communication between them. The latter can mainly open a certain port , Let the client and server establish communication.

3. WebSocket is a new protocol, different from http, its protocol format is ws://domain name or IP/url

4. Both it and http are application layer protocols, but the difference is that WebSocket can actively send messages to the client.

text:

After the above statement, we have a basic understanding of WebSocket and Socket. Let's start to explain the steps of SpringBoot integrating WebSocket

1. First introduce the dependency of WebSocket into the Pom file

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
 </dependency>

2. Add annotations to the Class class of Controller: @ServerEndpoint("url"). Note: @Component cannot be added to classes annotated by @ServerEndpoint annotations. Otherwise, the opening of the WebSocket connection will fail.

@ServerEndpoint("/web/socket/api")
public class WebSocketServer{
}

3. Create a monitoring event

    @OnOpen
    public void onOpen(Session session) {
        log.info("客户端:{}连接成功", session.getId());
        //业务代码.这里可以扩展记录本次连接的用户信息
    }

    @OnClose
    public void onClose(Session session) {
        log.info("客户端:{}连接断开", session.getId());
        //业务代码
    }

    @OnMessage
    public String onMsg(String message, Session session) {
        log.info("从客户端收到消息-->:{}", message);
        //业务代码
        //用户记录收到消息后的事件处理
        retrun "业务逻辑处理后的消息";
    }

4. Add WebSocket configuration class

@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig {

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

5. Use the online WebSocket website test after starting the project: websocket online test

6. Supplementary, in personal testing. After using @ServerEndpoint, classes managed by Spring cannot be injected. For example, some business Service interfaces cannot be injected through Autowired annotations. At this time, Bean injection can be performed through the context object instance.

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        ApplicationContextProvider.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
private final IWebSocketService socketService = ApplicationContextProvider.getBean(IWebSocketService.class);

Guess you like

Origin blog.csdn.net/qq_33351639/article/details/129118949