[Solution] websocket ws cannot be connected or cannot be connected

normal situation

The general error content is as shown in the figure:
insert image description here
There are many reasons for the failure of the WebSocket connection, mainly as follows:

  1. The server side does not configure WebSocket correctly, causing the client to fail to connect.

  2. Network problems, such as network instability, network delay, etc., cause the client to fail to connect.

  3. There is a problem with the client code that prevents it from connecting to the server properly.

  4. The firewall on the server side is improperly set, causing the client to fail to connect.

  5. The WebSocket server on the server side did not start correctly, causing the client to fail to connect.

code interception

The approximate content of the error report is shown in the figure:
insert image description here
It is obvious that the ws connection failed. At first I thought it was a problem with the request address, but I passed the reason after multiple checks.

wrong reason:

Because the way I wrote @ServerEndpoint. Need to inject ServerEndpointExporter, this bean will automatically register the Websocket endpoint declared with @ServerEndpoint annotation. It should be noted that if you use an independent servlet container instead of using springboot's built-in container directly, do not inject ServerEndpointExporter, because it will be provided and managed by the container itself.

Solution: add this configuration

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

Learning reference:

Guess you like

Origin blog.csdn.net/ruisasaki/article/details/131072417