How to Use WebSocket in Spring Boot: Simple Guide
To use
WebSocket in Spring Boot, add the spring-boot-starter-websocket dependency, create a configuration class with @EnableWebSocket, and implement a WebSocketHandler. Then register the handler with a URL endpoint to enable real-time communication.Syntax
Using WebSocket in Spring Boot involves these parts:
- Dependency: Add
spring-boot-starter-websocketto your project. - Configuration: Create a class with
@Configurationand@EnableWebSocketannotations. - Handler: Implement
WebSocketHandlerto handle messages. - Registration: Register the handler with a URL path in
WebSocketConfigurer.
java
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 org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.handler.TextWebSocketHandler; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/ws").setAllowedOrigins("*"); } public WebSocketHandler myHandler() { return new TextWebSocketHandler() { // override methods to handle messages }; } }
Example
This example shows a simple Spring Boot WebSocket setup that echoes messages back to the client.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 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 org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import org.springframework.web.socket.TextMessage; @SpringBootApplication public class WebSocketApp { public static void main(String[] args) { SpringApplication.run(WebSocketApp.class, args); } } @Configuration @EnableWebSocket class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new EchoHandler(), "/ws").setAllowedOrigins("*"); } } class EchoHandler extends TextWebSocketHandler { @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // Echo the received message back to the client session.sendMessage(new TextMessage("Echo: " + message.getPayload())); } }
Output
When a client connects to ws://localhost:8080/ws and sends a message, the server replies with "Echo: <your message>".
Common Pitfalls
- Forgetting to add
@EnableWebSocketon the configuration class disables WebSocket support. - Not setting
setAllowedOrigins("*")or proper origins causes connection failures due to CORS. - Using
WebSocketHandlerwithout overriding message methods results in no response. - Trying to use
@Controllerwith@MessageMappingrequires Spring Messaging and STOMP, which is different from raw WebSocketHandler usage.
java
/* Wrong: Missing @EnableWebSocket */ @Configuration public class WrongConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new EchoHandler(), "/ws").setAllowedOrigins("*"); } } /* Right: Add @EnableWebSocket */ @Configuration @EnableWebSocket public class RightConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new EchoHandler(), "/ws").setAllowedOrigins("*"); } }
Quick Reference
Summary tips for using WebSocket in Spring Boot:
- Add
spring-boot-starter-websocketdependency. - Create a
@Configurationclass with@EnableWebSocket. - Implement
WebSocketHandlerto handle messages. - Register handler with
WebSocketHandlerRegistryand set allowed origins. - Test with WebSocket clients like browser devtools or tools like
wscat.
Key Takeaways
Add spring-boot-starter-websocket and enable WebSocket with @EnableWebSocket.
Implement WebSocketHandler and register it with a URL endpoint.
Set allowed origins to avoid CORS issues during connection.
Override message handling methods to process WebSocket messages.
Use simple clients to test WebSocket endpoints during development.