springspring-bootspring-wsspring-websocket

spring boot websocket api 404 not found


In my spring boot app, I'm getting 404 error on the client side when I try to connect to the ws endpoint.

client side code

let wsUri = "ws://localhost:8080/chat"
let websocket = new WebSocket(wsUri);

spring config

package coffee.web;

import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

   @Override
   public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
       registry.addHandler(chatServer(), "/chat");
   }

   @Bean
   public ChatServer chatServer() {
       return new ChatServer();
   }
}

Solution

  • Since the request is handled by dispatcher servlet as normal http request. so you need to add @Controller annotation to the WebSocketConfig class

    @Configuration
    @EnableWebSocket
    @Controller
    public class WebSocketConfig implements WebSocketConfigurer