0
# Core WebSocket API
1
2
Essential WebSocket interfaces and classes for building WebSocket applications. Provides session management, message handling, and connection lifecycle support.
3
4
## Capabilities
5
6
### WebSocketHandler Interface
7
8
Main interface for handling WebSocket messages and lifecycle events.
9
10
```java { .api }
11
/**
12
* Central interface for handling WebSocket messages and lifecycle events.
13
* Implementations define application-specific WebSocket behavior.
14
*/
15
interface WebSocketHandler {
16
/**
17
* Called after the WebSocket connection has been established.
18
* @param session the WebSocket session
19
* @throws Exception if an error occurs
20
*/
21
void afterConnectionEstablished(WebSocketSession session) throws Exception;
22
23
/**
24
* Handle an incoming WebSocket message.
25
* @param session the WebSocket session
26
* @param message the incoming message
27
* @throws Exception if an error occurs
28
*/
29
void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
30
31
/**
32
* Handle a transport error during WebSocket communication.
33
* @param session the WebSocket session
34
* @param exception the transport error
35
* @throws Exception if an error occurs during error handling
36
*/
37
void handleTransportError(WebSocketSession session, Throwable exception) throws Exception;
38
39
/**
40
* Called after the WebSocket connection has been closed.
41
* @param session the WebSocket session
42
* @param closeStatus the close status
43
* @throws Exception if an error occurs
44
*/
45
void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
46
47
/**
48
* Whether the handler supports partial messages.
49
* @return true if partial messages are supported
50
*/
51
boolean supportsPartialMessages();
52
}
53
```
54
55
**Usage Example:**
56
57
```java
58
@Component
59
public class ChatWebSocketHandler implements WebSocketHandler {
60
private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();
61
62
@Override
63
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
64
sessions.add(session);
65
session.sendMessage(new TextMessage("Connected to chat"));
66
}
67
68
@Override
69
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
70
if (message instanceof TextMessage textMsg) {
71
String payload = textMsg.getPayload();
72
// Broadcast to all connected sessions
73
for (WebSocketSession s : sessions) {
74
if (s.isOpen()) {
75
s.sendMessage(new TextMessage("User: " + payload));
76
}
77
}
78
}
79
}
80
81
@Override
82
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
83
sessions.remove(session);
84
exception.printStackTrace();
85
}
86
87
@Override
88
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
89
sessions.remove(session);
90
}
91
92
@Override
93
public boolean supportsPartialMessages() {
94
return false;
95
}
96
}
97
```
98
99
### WebSocketSession Interface
100
101
Represents a WebSocket session, allows sending messages and managing the connection.
102
103
```java { .api }
104
/**
105
* Represents a WebSocket session between client and server.
106
* Provides methods for sending messages and managing the connection.
107
*/
108
interface WebSocketSession {
109
/**
110
* Get the unique session identifier.
111
* @return session ID
112
*/
113
String getId();
114
115
/**
116
* Get the URI of the WebSocket connection.
117
* @return connection URI or null if not available
118
*/
119
@Nullable URI getUri();
120
121
/**
122
* Get HTTP headers from the initial handshake.
123
* @return handshake headers
124
*/
125
HttpHeaders getHandshakeHeaders();
126
127
/**
128
* Get session attributes for storing application data.
129
* @return mutable map of session attributes
130
*/
131
Map<String, Object> getAttributes();
132
133
/**
134
* Get the authenticated user principal.
135
* @return user principal or null if not authenticated
136
*/
137
@Nullable Principal getPrincipal();
138
139
/**
140
* Get the local address of the connection.
141
* @return local socket address or null if not available
142
*/
143
@Nullable InetSocketAddress getLocalAddress();
144
145
/**
146
* Get the remote address of the connection.
147
* @return remote socket address or null if not available
148
*/
149
@Nullable InetSocketAddress getRemoteAddress();
150
151
/**
152
* Get the negotiated sub-protocol.
153
* @return accepted protocol or null if none negotiated
154
*/
155
@Nullable String getAcceptedProtocol();
156
157
/**
158
* Set the maximum size for text messages.
159
* @param messageSizeLimit max message size in bytes
160
*/
161
void setTextMessageSizeLimit(int messageSizeLimit);
162
163
/**
164
* Get the text message size limit.
165
* @return max text message size in bytes
166
*/
167
int getTextMessageSizeLimit();
168
169
/**
170
* Set the maximum size for binary messages.
171
* @param messageSizeLimit max message size in bytes
172
*/
173
void setBinaryMessageSizeLimit(int messageSizeLimit);
174
175
/**
176
* Get the binary message size limit.
177
* @return max binary message size in bytes
178
*/
179
int getBinaryMessageSizeLimit();
180
181
/**
182
* Get the negotiated WebSocket extensions.
183
* @return list of extensions
184
*/
185
List<WebSocketExtension> getExtensions();
186
187
/**
188
* Send a WebSocket message.
189
* @param message the message to send
190
* @throws IOException if sending fails
191
*/
192
void sendMessage(WebSocketMessage<?> message) throws IOException;
193
194
/**
195
* Check if the connection is open.
196
* @return true if connection is open
197
*/
198
boolean isOpen();
199
200
/**
201
* Close the connection with normal status.
202
* @throws IOException if closing fails
203
*/
204
void close() throws IOException;
205
206
/**
207
* Close the connection with specific status.
208
* @param status close status
209
* @throws IOException if closing fails
210
*/
211
void close(CloseStatus status) throws IOException;
212
}
213
```
214
215
**Usage Example:**
216
217
```java
218
@Component
219
public class SessionManagementHandler extends AbstractWebSocketHandler {
220
221
@Override
222
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
223
// Store user information in session attributes
224
Principal user = session.getPrincipal();
225
if (user != null) {
226
session.getAttributes().put("username", user.getName());
227
}
228
229
// Configure message size limits
230
session.setTextMessageSizeLimit(64 * 1024); // 64KB
231
session.setBinaryMessageSizeLimit(512 * 1024); // 512KB
232
233
// Send welcome message with session info
234
String welcome = String.format("Welcome! Session ID: %s, Remote: %s",
235
session.getId(), session.getRemoteAddress());
236
session.sendMessage(new TextMessage(welcome));
237
}
238
239
@Override
240
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
241
String username = (String) session.getAttributes().get("username");
242
if (username == null) {
243
session.close(CloseStatus.POLICY_VIOLATION.withReason("Authentication required"));
244
return;
245
}
246
247
// Process authenticated message
248
String response = String.format("[%s]: %s", username, message.getPayload());
249
session.sendMessage(new TextMessage(response));
250
}
251
}
252
```
253
254
### WebSocketMessage Interface
255
256
Represents a WebSocket message with typed payload.
257
258
```java { .api }
259
/**
260
* Base interface for WebSocket messages with typed payload.
261
* @param <T> the payload type
262
*/
263
interface WebSocketMessage<T> {
264
/**
265
* Get the message payload.
266
* @return message payload
267
*/
268
T getPayload();
269
270
/**
271
* Get payload size in bytes.
272
* @return payload size
273
*/
274
int getPayloadLength();
275
276
/**
277
* Check if this is the last part of a partial message.
278
* @return true if this is the last part
279
*/
280
boolean isLast();
281
}
282
```
283
284
### SubProtocolCapable Interface
285
286
Interface for WebSocket handlers that support sub-protocols.
287
288
```java { .api }
289
/**
290
* Interface for WebSocket handlers that support sub-protocols.
291
* Used for protocol negotiation during handshake.
292
*/
293
interface SubProtocolCapable {
294
/**
295
* Get the list of supported sub-protocols.
296
* @return list of protocol names
297
*/
298
List<String> getSubProtocols();
299
}
300
```
301
302
**Usage Example:**
303
304
```java
305
@Component
306
public class MultiProtocolHandler extends AbstractWebSocketHandler implements SubProtocolCapable {
307
308
@Override
309
public List<String> getSubProtocols() {
310
return Arrays.asList("chat", "echo", "broadcast");
311
}
312
313
@Override
314
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
315
String protocol = session.getAcceptedProtocol();
316
317
switch (protocol) {
318
case "chat" -> handleChatMessage(session, message);
319
case "echo" -> session.sendMessage(message);
320
case "broadcast" -> broadcastMessage(message);
321
default -> session.sendMessage(new TextMessage("Unsupported protocol: " + protocol));
322
}
323
}
324
325
private void handleChatMessage(WebSocketSession session, TextMessage message) throws Exception {
326
// Chat-specific logic
327
}
328
329
private void broadcastMessage(TextMessage message) throws Exception {
330
// Broadcast-specific logic
331
}
332
}
333
```
334
335