Spring WebSocket provides comprehensive WebSocket support for Spring applications including both low-level WebSocket API support and higher-level SockJS fallback options
npx @tessl/cli install tessl/maven-org-springframework--spring-websocket@6.2.0Spring WebSocket provides comprehensive WebSocket support for Spring applications, enabling real-time bidirectional communication between web browsers and servers. It includes full support for the standard WebSocket API with Spring-specific abstractions, SockJS transport fallback mechanisms, integration with Spring Security, STOMP protocol support, and seamless integration with Spring's dependency injection and configuration frameworks.
pom.xml:<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>6.2.8</version>
</dependency>For Gradle:
implementation 'org.springframework:spring-websocket:6.2.8'import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("Connection established: " + session.getId());
session.sendMessage(new TextMessage("Welcome!"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("Received: " + payload);
// Echo the message back
session.sendMessage(new TextMessage("Echo: " + payload));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("Connection closed: " + session.getId());
}
}Spring WebSocket is built around several key components:
WebSocketHandler, WebSocketSession, and message types for handling WebSocket communicationEssential WebSocket interfaces and classes for building WebSocket applications. Provides session management, message handling, and connection lifecycle support.
interface WebSocketHandler {
void afterConnectionEstablished(WebSocketSession session) throws Exception;
void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
void handleTransportError(WebSocketSession session, Throwable exception) throws Exception;
void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
boolean supportsPartialMessages();
}
interface WebSocketSession {
String getId();
URI getUri();
Map<String, Object> getAttributes();
Principal getPrincipal();
void sendMessage(WebSocketMessage<?> message) throws IOException;
boolean isOpen();
void close() throws IOException;
void close(CloseStatus status) throws IOException;
}WebSocket message implementations for different data types including text, binary, ping, and pong messages.
class TextMessage extends AbstractWebSocketMessage<String> {
public TextMessage(CharSequence payload);
public TextMessage(CharSequence payload, boolean isLast);
public byte[] asBytes();
}
class BinaryMessage extends AbstractWebSocketMessage<ByteBuffer> {
public BinaryMessage(ByteBuffer payload);
public BinaryMessage(ByteBuffer payload, boolean isLast);
public BinaryMessage(byte[] payload);
}
class PingMessage extends AbstractWebSocketMessage<ByteBuffer> {
public PingMessage();
public PingMessage(ByteBuffer payload);
}
class PongMessage extends AbstractWebSocketMessage<ByteBuffer> {
public PongMessage();
public PongMessage(ByteBuffer payload);
}Annotation-based and XML configuration for registering WebSocket handlers and configuring STOMP messaging support.
@EnableWebSocket
@Configuration
class WebSocketConfig implements WebSocketConfigurer {
void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
}
@EnableWebSocketMessageBroker
@Configuration
class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
void registerStompEndpoints(StompEndpointRegistry registry);
void configureMessageBroker(MessageBrokerRegistry registry);
}WebSocket handler implementations and decorators for building robust WebSocket applications with cross-cutting concerns.
abstract class AbstractWebSocketHandler implements WebSocketHandler {
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception;
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception;
protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception;
}
class TextWebSocketHandler extends AbstractWebSocketHandler;
class BinaryWebSocketHandler extends AbstractWebSocketHandler;
class WebSocketHandlerDecorator implements WebSocketHandler {
public WebSocketHandlerDecorator(WebSocketHandler delegate);
public WebSocketHandler getDelegate();
}WebSocket client implementations for establishing outbound WebSocket connections with connection management.
interface WebSocketClient {
ListenableFuture<WebSocketSession> doHandshake(
WebSocketHandler webSocketHandler,
String uriTemplate,
Object... uriVariables
);
ListenableFuture<WebSocketSession> doHandshake(
WebSocketHandler webSocketHandler,
WebSocketHttpHeaders headers,
URI uri
);
}
class WebSocketConnectionManager extends ConnectionManagerSupport {
public WebSocketConnectionManager(
WebSocketClient client,
WebSocketHandler webSocketHandler,
String uriTemplate,
Object... uriVariables
);
}STOMP (Simple Text Oriented Messaging Protocol) support for higher-level messaging patterns over WebSocket connections.
interface SubProtocolHandler {
List<String> getSupportedProtocols();
void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> message, MessageChannel outputChannel);
void handleMessageToClient(WebSocketSession session, Message<?> message);
}
class StompSubProtocolHandler implements SubProtocolHandler;
class WebSocketStompClient {
public WebSocketStompClient(WebSocketClient webSocketClient);
public void setMessageConverter(MessageConverter messageConverter);
}Server-side WebSocket support with handshake handling and upgrade strategies for different server implementations.
interface HandshakeHandler {
boolean doHandshake(
ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes
) throws HandshakeFailureException;
}
interface RequestUpgradeStrategy {
String[] getSupportedVersions();
void upgrade(
ServerHttpRequest request,
ServerHttpResponse response,
String selectedProtocol,
List<WebSocketExtension> selectedExtensions,
Principal user,
WebSocketHandler wsHandler,
Map<String, Object> attrs
) throws HandshakeFailureException;
}SockJS fallback support providing WebSocket-like object in browsers that don't support WebSocket natively, with multiple transport options.
interface SockJsService {
void handleRequest(
ServerHttpRequest request,
ServerHttpResponse response,
String sockJsPath,
WebSocketHandler webSocketHandler
) throws SockJsException;
}
enum TransportType {
WEBSOCKET, XHR, XHR_STREAMING, XHR_POLLING,
JSONP, JSONP_POLLING, HTML_FILE, EVENT_SOURCE;
}
interface SockJsSession extends WebSocketSession {
String getId();
void close() throws IOException;
void close(CloseStatus status) throws IOException;
}final class CloseStatus {
public static final CloseStatus NORMAL; // 1000
public static final CloseStatus GOING_AWAY; // 1001
public static final CloseStatus PROTOCOL_ERROR; // 1002
public static final CloseStatus NOT_ACCEPTABLE; // 1003
public static final CloseStatus NO_STATUS_CODE; // 1005
public static final CloseStatus NO_CLOSE_FRAME; // 1006
public static final CloseStatus BAD_DATA; // 1007
public static final CloseStatus POLICY_VIOLATION; // 1008
public static final CloseStatus TOO_BIG_TO_PROCESS; // 1009
public static final CloseStatus REQUIRED_EXTENSION; // 1010
public static final CloseStatus SERVER_ERROR; // 1011
public static final CloseStatus SERVICE_RESTARTED; // 1012
public static final CloseStatus SERVICE_OVERLOAD; // 1013
public static final CloseStatus TLS_HANDSHAKE_FAILURE; // 1015
public static final CloseStatus SESSION_NOT_RELIABLE; // 4500
public CloseStatus(int code);
public CloseStatus(int code, @Nullable String reason);
public int getCode();
@Nullable public String getReason();
public CloseStatus withReason(String reason);
}
class WebSocketExtension {
public WebSocketExtension(String name);
public WebSocketExtension(String name, @Nullable Map<String, String> parameters);
public String getName();
public Map<String, String> getParameters();
public static List<WebSocketExtension> parseExtensions(@Nullable String extensions);
}
class WebSocketHttpHeaders extends HttpHeaders {
public void setSecWebSocketAccept(@Nullable String secWebSocketAccept);
@Nullable public String getSecWebSocketAccept();
public List<WebSocketExtension> getSecWebSocketExtensions();
public void setSecWebSocketExtensions(List<WebSocketExtension> extensions);
public List<String> getSecWebSocketProtocol();
public void setSecWebSocketProtocol(String... secWebSocketProtocols);
public void setSecWebSocketVersion(@Nullable String secWebSocketVersion);
@Nullable public String getSecWebSocketVersion();
public void setSecWebSocketKey(@Nullable String secWebSocketKey);
@Nullable public String getSecWebSocketKey();
}