0
# Spring WebSocket
1
2
Spring 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.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-websocket
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven `pom.xml`:
10
11
```xml
12
<dependency>
13
<groupId>org.springframework</groupId>
14
<artifactId>spring-websocket</artifactId>
15
<version>6.2.8</version>
16
</dependency>
17
```
18
19
For Gradle:
20
21
```gradle
22
implementation 'org.springframework:spring-websocket:6.2.8'
23
```
24
25
## Core Imports
26
27
```java
28
import org.springframework.web.socket.WebSocketHandler;
29
import org.springframework.web.socket.WebSocketSession;
30
import org.springframework.web.socket.WebSocketMessage;
31
import org.springframework.web.socket.TextMessage;
32
import org.springframework.web.socket.BinaryMessage;
33
import org.springframework.web.socket.CloseStatus;
34
```
35
36
## Basic Usage
37
38
```java
39
import org.springframework.web.socket.*;
40
import org.springframework.web.socket.handler.TextWebSocketHandler;
41
42
@Component
43
public class MyWebSocketHandler extends TextWebSocketHandler {
44
45
@Override
46
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
47
System.out.println("Connection established: " + session.getId());
48
session.sendMessage(new TextMessage("Welcome!"));
49
}
50
51
@Override
52
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
53
String payload = message.getPayload();
54
System.out.println("Received: " + payload);
55
56
// Echo the message back
57
session.sendMessage(new TextMessage("Echo: " + payload));
58
}
59
60
@Override
61
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
62
System.out.println("Connection closed: " + session.getId());
63
}
64
}
65
```
66
67
## Architecture
68
69
Spring WebSocket is built around several key components:
70
71
- **Core WebSocket APIs**: `WebSocketHandler`, `WebSocketSession`, and message types for handling WebSocket communication
72
- **Adapter Layer**: Integration with different WebSocket implementations (JSR-356, Jetty) through adapters
73
- **Configuration**: Both annotation-based and XML configuration support for registering handlers and endpoints
74
- **Handler Framework**: Extensible handler system with decorators for cross-cutting concerns
75
- **Messaging Integration**: Full STOMP protocol support with Spring messaging framework integration
76
- **Server Integration**: Support for multiple server implementations (Tomcat, Jetty, Undertow, etc.)
77
- **SockJS Support**: Complete fallback solution with 8 different transport types for browsers without WebSocket support
78
79
## Capabilities
80
81
### Core WebSocket API
82
83
Essential WebSocket interfaces and classes for building WebSocket applications. Provides session management, message handling, and connection lifecycle support.
84
85
```java { .api }
86
interface WebSocketHandler {
87
void afterConnectionEstablished(WebSocketSession session) throws Exception;
88
void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
89
void handleTransportError(WebSocketSession session, Throwable exception) throws Exception;
90
void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
91
boolean supportsPartialMessages();
92
}
93
94
interface WebSocketSession {
95
String getId();
96
URI getUri();
97
Map<String, Object> getAttributes();
98
Principal getPrincipal();
99
void sendMessage(WebSocketMessage<?> message) throws IOException;
100
boolean isOpen();
101
void close() throws IOException;
102
void close(CloseStatus status) throws IOException;
103
}
104
```
105
106
[Core WebSocket API](./core-websocket-api.md)
107
108
### Message Types
109
110
WebSocket message implementations for different data types including text, binary, ping, and pong messages.
111
112
```java { .api }
113
class TextMessage extends AbstractWebSocketMessage<String> {
114
public TextMessage(CharSequence payload);
115
public TextMessage(CharSequence payload, boolean isLast);
116
public byte[] asBytes();
117
}
118
119
class BinaryMessage extends AbstractWebSocketMessage<ByteBuffer> {
120
public BinaryMessage(ByteBuffer payload);
121
public BinaryMessage(ByteBuffer payload, boolean isLast);
122
public BinaryMessage(byte[] payload);
123
}
124
125
class PingMessage extends AbstractWebSocketMessage<ByteBuffer> {
126
public PingMessage();
127
public PingMessage(ByteBuffer payload);
128
}
129
130
class PongMessage extends AbstractWebSocketMessage<ByteBuffer> {
131
public PongMessage();
132
public PongMessage(ByteBuffer payload);
133
}
134
```
135
136
[Message Types](./message-types.md)
137
138
### Configuration Support
139
140
Annotation-based and XML configuration for registering WebSocket handlers and configuring STOMP messaging support.
141
142
```java { .api }
143
@EnableWebSocket
144
@Configuration
145
class WebSocketConfig implements WebSocketConfigurer {
146
void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
147
}
148
149
@EnableWebSocketMessageBroker
150
@Configuration
151
class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
152
void registerStompEndpoints(StompEndpointRegistry registry);
153
void configureMessageBroker(MessageBrokerRegistry registry);
154
}
155
```
156
157
[Configuration](./configuration.md)
158
159
### Handler Framework
160
161
WebSocket handler implementations and decorators for building robust WebSocket applications with cross-cutting concerns.
162
163
```java { .api }
164
abstract class AbstractWebSocketHandler implements WebSocketHandler {
165
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception;
166
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception;
167
protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception;
168
}
169
170
class TextWebSocketHandler extends AbstractWebSocketHandler;
171
class BinaryWebSocketHandler extends AbstractWebSocketHandler;
172
173
class WebSocketHandlerDecorator implements WebSocketHandler {
174
public WebSocketHandlerDecorator(WebSocketHandler delegate);
175
public WebSocketHandler getDelegate();
176
}
177
```
178
179
[Handler Framework](./handler-framework.md)
180
181
### Client Support
182
183
WebSocket client implementations for establishing outbound WebSocket connections with connection management.
184
185
```java { .api }
186
interface WebSocketClient {
187
ListenableFuture<WebSocketSession> doHandshake(
188
WebSocketHandler webSocketHandler,
189
String uriTemplate,
190
Object... uriVariables
191
);
192
ListenableFuture<WebSocketSession> doHandshake(
193
WebSocketHandler webSocketHandler,
194
WebSocketHttpHeaders headers,
195
URI uri
196
);
197
}
198
199
class WebSocketConnectionManager extends ConnectionManagerSupport {
200
public WebSocketConnectionManager(
201
WebSocketClient client,
202
WebSocketHandler webSocketHandler,
203
String uriTemplate,
204
Object... uriVariables
205
);
206
}
207
```
208
209
[Client Support](./client-support.md)
210
211
### STOMP Messaging
212
213
STOMP (Simple Text Oriented Messaging Protocol) support for higher-level messaging patterns over WebSocket connections.
214
215
```java { .api }
216
interface SubProtocolHandler {
217
List<String> getSupportedProtocols();
218
void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> message, MessageChannel outputChannel);
219
void handleMessageToClient(WebSocketSession session, Message<?> message);
220
}
221
222
class StompSubProtocolHandler implements SubProtocolHandler;
223
224
class WebSocketStompClient {
225
public WebSocketStompClient(WebSocketClient webSocketClient);
226
public void setMessageConverter(MessageConverter messageConverter);
227
}
228
```
229
230
[STOMP Messaging](./stomp-messaging.md)
231
232
### Server Integration
233
234
Server-side WebSocket support with handshake handling and upgrade strategies for different server implementations.
235
236
```java { .api }
237
interface HandshakeHandler {
238
boolean doHandshake(
239
ServerHttpRequest request,
240
ServerHttpResponse response,
241
WebSocketHandler wsHandler,
242
Map<String, Object> attributes
243
) throws HandshakeFailureException;
244
}
245
246
interface RequestUpgradeStrategy {
247
String[] getSupportedVersions();
248
void upgrade(
249
ServerHttpRequest request,
250
ServerHttpResponse response,
251
String selectedProtocol,
252
List<WebSocketExtension> selectedExtensions,
253
Principal user,
254
WebSocketHandler wsHandler,
255
Map<String, Object> attrs
256
) throws HandshakeFailureException;
257
}
258
```
259
260
[Server Integration](./server-integration.md)
261
262
### SockJS Support
263
264
SockJS fallback support providing WebSocket-like object in browsers that don't support WebSocket natively, with multiple transport options.
265
266
```java { .api }
267
interface SockJsService {
268
void handleRequest(
269
ServerHttpRequest request,
270
ServerHttpResponse response,
271
String sockJsPath,
272
WebSocketHandler webSocketHandler
273
) throws SockJsException;
274
}
275
276
enum TransportType {
277
WEBSOCKET, XHR, XHR_STREAMING, XHR_POLLING,
278
JSONP, JSONP_POLLING, HTML_FILE, EVENT_SOURCE;
279
}
280
281
interface SockJsSession extends WebSocketSession {
282
String getId();
283
void close() throws IOException;
284
void close(CloseStatus status) throws IOException;
285
}
286
```
287
288
[SockJS Support](./sockjs-support.md)
289
290
## Types
291
292
```java { .api }
293
final class CloseStatus {
294
public static final CloseStatus NORMAL; // 1000
295
public static final CloseStatus GOING_AWAY; // 1001
296
public static final CloseStatus PROTOCOL_ERROR; // 1002
297
public static final CloseStatus NOT_ACCEPTABLE; // 1003
298
public static final CloseStatus NO_STATUS_CODE; // 1005
299
public static final CloseStatus NO_CLOSE_FRAME; // 1006
300
public static final CloseStatus BAD_DATA; // 1007
301
public static final CloseStatus POLICY_VIOLATION; // 1008
302
public static final CloseStatus TOO_BIG_TO_PROCESS; // 1009
303
public static final CloseStatus REQUIRED_EXTENSION; // 1010
304
public static final CloseStatus SERVER_ERROR; // 1011
305
public static final CloseStatus SERVICE_RESTARTED; // 1012
306
public static final CloseStatus SERVICE_OVERLOAD; // 1013
307
public static final CloseStatus TLS_HANDSHAKE_FAILURE; // 1015
308
public static final CloseStatus SESSION_NOT_RELIABLE; // 4500
309
310
public CloseStatus(int code);
311
public CloseStatus(int code, @Nullable String reason);
312
public int getCode();
313
@Nullable public String getReason();
314
public CloseStatus withReason(String reason);
315
}
316
317
class WebSocketExtension {
318
public WebSocketExtension(String name);
319
public WebSocketExtension(String name, @Nullable Map<String, String> parameters);
320
public String getName();
321
public Map<String, String> getParameters();
322
public static List<WebSocketExtension> parseExtensions(@Nullable String extensions);
323
}
324
325
class WebSocketHttpHeaders extends HttpHeaders {
326
public void setSecWebSocketAccept(@Nullable String secWebSocketAccept);
327
@Nullable public String getSecWebSocketAccept();
328
public List<WebSocketExtension> getSecWebSocketExtensions();
329
public void setSecWebSocketExtensions(List<WebSocketExtension> extensions);
330
public List<String> getSecWebSocketProtocol();
331
public void setSecWebSocketProtocol(String... secWebSocketProtocols);
332
public void setSecWebSocketVersion(@Nullable String secWebSocketVersion);
333
@Nullable public String getSecWebSocketVersion();
334
public void setSecWebSocketKey(@Nullable String secWebSocketKey);
335
@Nullable public String getSecWebSocketKey();
336
}
337
```