0
# WebSocket Support
1
2
WebSocket capabilities for both servlet and reactive applications with Jakarta WebSocket API support. Provides comprehensive WebSocket server configuration and customization for real-time communication applications.
3
4
## Capabilities
5
6
### Servlet WebSocket Support
7
8
WebSocket configuration for traditional servlet-based Spring Boot applications using Jakarta WebSocket API.
9
10
```java { .api }
11
/**
12
* WebSocket customizer for Jetty servlet web servers
13
*/
14
public class JettyWebSocketServletWebServerCustomizer
15
implements WebServerFactoryCustomizer<JettyServletWebServerFactory> {
16
17
/** Create servlet WebSocket customizer */
18
public JettyWebSocketServletWebServerCustomizer();
19
20
/** Apply WebSocket configuration to servlet factory */
21
public void customize(JettyServletWebServerFactory factory);
22
23
/** Configure WebSocket policy settings */
24
public void configureWebSocketPolicy(WebSocketPolicy policy);
25
26
/** Set WebSocket idle timeout */
27
public void setIdleTimeout(Duration idleTimeout);
28
29
/** Set maximum WebSocket message size */
30
public void setMaxTextMessageSize(int maxTextMessageSize);
31
public void setMaxBinaryMessageSize(int maxBinaryMessageSize);
32
33
/** Set maximum WebSocket frame size */
34
public void setMaxTextMessageBufferSize(int maxTextMessageBufferSize);
35
public void setMaxBinaryMessageBufferSize(int maxBinaryMessageBufferSize);
36
}
37
```
38
39
**Servlet WebSocket Configuration Example:**
40
41
```java
42
@Configuration
43
@EnableWebSocket
44
public class JettyWebSocketServletConfig implements WebSocketConfigurer {
45
46
@Override
47
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
48
registry.addHandler(new MyWebSocketHandler(), "/websocket")
49
.setAllowedOrigins("*");
50
}
51
52
@Bean
53
public JettyServletWebServerFactory jettyFactory() {
54
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
55
56
factory.addServerCustomizers(server -> {
57
// Configure WebSocket
58
ServletContextHandler context = new ServletContextHandler();
59
context.setContextPath("/");
60
61
// Add WebSocket upgrade filter
62
WebSocketUpgradeFilter.configure(context);
63
64
// Configure WebSocket mapping
65
JettyWebSocketServletContainerInitializer.configure(context,
66
(servletContext, wsContainer) -> {
67
wsContainer.setDefaultMaxTextMessageBufferSize(65536);
68
wsContainer.setDefaultMaxBinaryMessageBufferSize(65536);
69
wsContainer.setDefaultMaxSessionIdleTimeout(300000);
70
});
71
72
server.setHandler(context);
73
});
74
75
return factory;
76
}
77
}
78
79
@Component
80
public class MyWebSocketHandler extends TextWebSocketHandler {
81
82
@Override
83
public void afterConnectionEstablished(WebSocketSession session) {
84
// Handle connection establishment
85
}
86
87
@Override
88
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
89
// Handle text messages
90
}
91
}
92
```
93
94
### Reactive WebSocket Support
95
96
WebSocket configuration for reactive Spring WebFlux applications with non-blocking WebSocket handling.
97
98
```java { .api }
99
/**
100
* WebSocket customizer for Jetty reactive web servers
101
*/
102
public class JettyWebSocketReactiveWebServerCustomizer
103
implements WebServerFactoryCustomizer<JettyReactiveWebServerFactory> {
104
105
/** Create reactive WebSocket customizer */
106
public JettyWebSocketReactiveWebServerCustomizer();
107
108
/** Apply WebSocket configuration to reactive factory */
109
public void customize(JettyReactiveWebServerFactory factory);
110
111
/** Configure reactive WebSocket policy */
112
public void configureReactiveWebSocketPolicy(WebSocketPolicy policy);
113
114
/** Set reactive WebSocket connection timeout */
115
public void setConnectionTimeout(Duration connectionTimeout);
116
117
/** Configure WebSocket frame handling */
118
public void setMaxFrameSize(int maxFrameSize);
119
public void setInputBufferSize(int inputBufferSize);
120
public void setOutputBufferSize(int outputBufferSize);
121
}
122
```
123
124
**Reactive WebSocket Configuration Example:**
125
126
```java
127
@Configuration
128
public class JettyReactiveWebSocketConfig {
129
130
@Bean
131
public WebSocketHandlerAdapter webSocketHandlerAdapter() {
132
return new WebSocketHandlerAdapter();
133
}
134
135
@Bean
136
public HandlerMapping webSocketHandlerMapping() {
137
Map<String, WebSocketHandler> map = new HashMap<>();
138
map.put("/websocket", new ReactiveWebSocketHandler());
139
140
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
141
handlerMapping.setOrder(1);
142
handlerMapping.setUrlMap(map);
143
return handlerMapping;
144
}
145
146
@Bean
147
public JettyReactiveWebServerFactory jettyReactiveFactory() {
148
JettyReactiveWebServerFactory factory = new JettyReactiveWebServerFactory();
149
150
factory.addServerCustomizers(server -> {
151
// Configure WebSocket support
152
ServletContextHandler context = new ServletContextHandler();
153
154
JettyWebSocketServletContainerInitializer.configure(context,
155
(servletContext, wsContainer) -> {
156
wsContainer.setDefaultMaxTextMessageBufferSize(131072);
157
wsContainer.setDefaultMaxBinaryMessageBufferSize(131072);
158
wsContainer.setDefaultMaxSessionIdleTimeout(600000);
159
});
160
161
server.setHandler(context);
162
});
163
164
return factory;
165
}
166
}
167
168
@Component
169
public class ReactiveWebSocketHandler implements WebSocketHandler {
170
171
@Override
172
public Mono<Void> handle(WebSocketSession session) {
173
return session.send(
174
session.receive()
175
.map(WebSocketMessage::getPayloadAsText)
176
.map(text -> "Echo: " + text)
177
.map(session::textMessage)
178
);
179
}
180
}
181
```
182
183
### WebSocket Policy Configuration
184
185
Detailed WebSocket policy configuration for connection management and resource limits.
186
187
```java { .api }
188
/**
189
* WebSocket policy configuration for Jetty
190
*/
191
public class WebSocketPolicy {
192
193
/** Create WebSocket policy with default settings */
194
public WebSocketPolicy();
195
196
/** Create WebSocket policy for specific behavior */
197
public WebSocketPolicy(WebSocketBehavior behavior);
198
199
/** Set idle timeout for WebSocket connections */
200
public void setIdleTimeout(long idleTimeout);
201
202
/** Set maximum text message size */
203
public void setMaxTextMessageSize(int maxTextMessageSize);
204
205
/** Set maximum binary message size */
206
public void setMaxBinaryMessageSize(int maxBinaryMessageSize);
207
208
/** Set maximum text message buffer size */
209
public void setMaxTextMessageBufferSize(int maxTextMessageBufferSize);
210
211
/** Set maximum binary message buffer size */
212
public void setMaxBinaryMessageBufferSize(int maxBinaryMessageBufferSize);
213
214
/** Set input buffer size */
215
public void setInputBufferSize(int inputBufferSize);
216
217
/** Set output buffer size */
218
public void setOutputBufferSize(int outputBufferSize);
219
220
/** Set async write timeout */
221
public void setAsyncWriteTimeout(long asyncWriteTimeout);
222
223
/** Enable/disable auto-fragment messages */
224
public void setAutoFragment(boolean autoFragment);
225
}
226
```
227
228
### Jakarta WebSocket API Integration
229
230
Integration with Jakarta WebSocket API for standard WebSocket endpoint support.
231
232
```java { .api }
233
/**
234
* Jakarta WebSocket configuration for Jetty
235
*/
236
public class JettyWebSocketConfiguration {
237
238
/** Configure Jakarta WebSocket container */
239
public static void configureWebSocketContainer(
240
ServletContext servletContext,
241
ServerContainer serverContainer);
242
243
/** Add WebSocket endpoint */
244
public static void addEndpoint(ServerContainer container,
245
Class<?> endpointClass);
246
247
/** Configure WebSocket decoder/encoder */
248
public static void configureCodecs(ServerContainer container,
249
List<Class<? extends Decoder>> decoders,
250
List<Class<? extends Encoder>> encoders);
251
}
252
```
253
254
**Jakarta WebSocket Endpoint Example:**
255
256
```java
257
@ServerEndpoint(
258
value = "/websocket/{userId}",
259
decoders = MessageDecoder.class,
260
encoders = MessageEncoder.class
261
)
262
@Component
263
public class WebSocketEndpoint {
264
265
@OnOpen
266
public void onOpen(Session session, @PathParam("userId") String userId) {
267
// Handle connection open
268
session.getUserProperties().put("userId", userId);
269
}
270
271
@OnMessage
272
public void onMessage(Session session, Message message) {
273
// Handle incoming message
274
try {
275
session.getBasicRemote().sendObject(
276
new Message("Echo: " + message.getContent()));
277
} catch (Exception e) {
278
// Handle error
279
}
280
}
281
282
@OnClose
283
public void onClose(Session session, CloseReason closeReason) {
284
// Handle connection close
285
}
286
287
@OnError
288
public void onError(Session session, Throwable throwable) {
289
// Handle error
290
}
291
}
292
```
293
294
### WebSocket Extensions
295
296
Support for WebSocket extensions like per-message-deflate compression.
297
298
```java { .api }
299
/**
300
* WebSocket extension configuration
301
*/
302
public class WebSocketExtensionConfiguration {
303
304
/** Configure per-message-deflate extension */
305
public static void configureDeflateExtension(
306
WebSocketServletFactory factory,
307
boolean serverNoContextTakeover,
308
boolean clientNoContextTakeover,
309
int compressionLevel);
310
311
/** Add custom WebSocket extension */
312
public static void addExtension(WebSocketServletFactory factory,
313
ExtensionConfig extensionConfig);
314
315
/** Configure extension parameters */
316
public static ExtensionConfig createExtensionConfig(
317
String extensionName,
318
Map<String, String> parameters);
319
}
320
```
321
322
**WebSocket Extension Configuration:**
323
324
```java
325
@Configuration
326
public class WebSocketExtensionConfig {
327
328
@Bean
329
public JettyServletWebServerFactory jettyFactoryWithExtensions() {
330
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
331
332
factory.addServerCustomizers(server -> {
333
ServletContextHandler context = new ServletContextHandler();
334
335
JettyWebSocketServletContainerInitializer.configure(context,
336
(servletContext, wsContainer) -> {
337
// Configure per-message-deflate extension
338
wsContainer.addExtension("permessage-deflate");
339
340
// Set compression parameters
341
WebSocketPolicy policy = wsContainer.getPolicy();
342
policy.setInputBufferSize(8192);
343
policy.setOutputBufferSize(8192);
344
});
345
346
server.setHandler(context);
347
});
348
349
return factory;
350
}
351
}
352
```