How to Integrate WebSocket into Spring Boot for Real‑Time Communication
This guide shows how to add Spring Boot WebSocket support, configure a server endpoint, implement lifecycle callbacks, and secure connections with JWT validation, providing a complete solution for high‑frequency real‑time data exchange.
What is WebSocket
WebSocket is an HTML5‑defined protocol that enables full‑duplex communication over a single TCP connection, allowing browsers and servers to exchange data anytime without the overhead of repeated HTTP handshakes.
Environment preparation
Add the WebSocket starter alongside the basic web starter in pom.xml:
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Web dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- WebSocket dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
</dependencies>Configure the WebSocket server
Create a configuration class that registers ServerEndpointExporter as a Spring bean, which automatically detects @ServerEndpoint annotations.
@Configuration
public class WebSocketConfig {
/**
* Inject ServerEndpointExporter; the bean will auto‑register any class annotated with @ServerEndpoint.
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}Implement a WebSocket endpoint
Annotate a component with @ServerEndpoint, specify the URL path and an optional configurator for authentication.
@Component
@Slf4j
@ServerEndpoint(value = "/detail", configurator = WebSocketAuthConfig.class)
public class DetailServer {
// lifecycle methods are defined below
}Define lifecycle callbacks using the standard annotations: @OnOpen: called when a new client connects. @OnClose: called when a connection is closed. @OnMessage: called when a message arrives. @OnError: called on errors.
@OnOpen
public void onOpen(Session session) {
// store session if needed
log.info("【websocket消息】有新的连接");
}
@OnClose
public void onClose() {
// clean up session
log.info("【websocket消息】连接断开");
}
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端消息:" + message);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误,原因:" + error.getMessage());
}To push data to the client, use the asynchronous remote endpoint:
session.getAsyncRemote().sendText(message);Authorization and token validation
Secure the endpoint by extending ServerEndpointConfig.Configurator and overriding checkOrigin to verify a JWT token passed as a request parameter.
@Slf4j
public class WebSocketAuthConfig extends ServerEndpointConfig.Configurator {
/**
* Intercept the WebSocket handshake and validate the token.
*/
@Override
public boolean checkOrigin(final String originHeaderValue) {
final ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
try {
assert attrs != null;
JwtUtil jwtUtil = SpringUtil.getBean(JwtUtil.class);
HttpServletRequest request = attrs.getRequest();
String token = request.getParameter("token");
Claims claims = jwtUtil.getClaimsByToken(token);
if (ObjectUtil.isNull(claims)) {
log.info("Token错误,拒绝连接......");
request.getSession().setAttribute("loginFill", true);
return false;
} else {
request.getSession().setAttribute("loginFill", false);
}
} catch (Exception e) {
log.error("WebSocket-auth-error", e);
}
return true;
}
}Alternatively, Shiro can be used to intercept requests via ServerEndpointConfig.Configurator without writing custom code.
Conclusion
By following these steps you obtain a fully functional Spring Boot WebSocket endpoint capable of handling real‑time data streams and performing JWT‑based authentication. For extreme concurrency scenarios, a Netty‑based implementation may offer higher performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Dunmao Tech Hub
Sharing selected technical articles synced from CSDN. Follow us on CSDN: Dunmao.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
