Client configuration
Each client is configured under spring.websocket.client.config.<name>.*, where <name> is the client's name; what a client does not set falls back to spring.websocket.client.config.default.*. Two keys for all clients limit the size of incoming messages. Tokens go into the handshake through WebSocketHandshakeInterceptor beans.
Why
A mobile app on a flaky network needs a quick first reconnect and a long maximum pause; a server-to-server feed needs a fixed retry and a limit. The server wants a fresh token at every reconnection. Properties and interceptors cover these without touching the client interface.
Example
spring.websocket.client.config.default.connect-timeout=5s
spring.websocket.client.config.chat.url=wss://chat.neon.books/ws
spring.websocket.client.config.chat.reconnect.delay=500ms
spring.websocket.client.config.chat.reconnect.jitter=100ms
spring.websocket.client.config.chat.reconnect.max-retries=10
spring.websocket.client.config.feed.default-request-headers.X-Api-Key=${FEED_KEY}
spring.websocket.client.max-text-message-size=1MB
// The chat server wants the user's current token, at every (re)connection.
@Component()
class ChatAuth implements WebSocketHandshakeInterceptor {
ChatAuth(this.tokens);
final TokenStore tokens;
@override
Future<void> apply(WebSocketHandshake handshake) async {
if (handshake.clientName == 'chat') { // other clients are left alone
handshake.queryParameter('token', await tokens.current());
// VM and mobile only: handshake.headers.set('Authorization', 'Bearer ...');
}
}
}
Client keys
Each key is spring.websocket.client.config.<name>.<key> (or default):
| Key | Default | Meaning |
|---|---|---|
url |
none | The address when @WebSocketClient has no url; ${...} placeholders allowed. |
connect-timeout |
10s |
The longest a handshake may take. |
reconnect.enabled |
true |
Open lost connections again while someone listens. With false, a lost connection ends the message streams. |
reconnect.delay |
1s |
The wait before the first attempt. |
reconnect.multiplier |
2 |
What each further wait is multiplied by; 1 for a fixed delay, not less. |
reconnect.max-delay |
30s |
The longest wait; positive. |
reconnect.jitter |
none | A random part added to or taken from each wait. It grows with the multiplier like the wait does, and the wait never goes below delay nor above max-delay. |
reconnect.max-retries |
no limit | Attempts in a row before giving up. |
default-request-headers.<Name> |
none | Headers sent with every handshake (not possible in browsers). A comma list or a YAML list gives several values. A client's header replaces the default one of the same name, in any case. |
- The
reconnect.*names are those of Spring Framework 7'sRetryPolicy, and the values are checked as its builder checks them:delayandjitternot negative,multiplierat least 1,max-delaypositive,max-retriesnot negative. Adelayabovemax-delaywaitsmax-delay. Anything else fails the start naming the property (amultiplierormax-retriesthat is not a number fails with a plainFormatException). - The waits are computed as by Spring's
ExponentialBackOff. The defaults suit reconnecting (a doubling delay, no limit) rather thanRetryPolicy's (a fixed 1 s delay, 3 retries). reconnect.enabledtakestrue/falsein any case, alsoon/off,yes/no,1/0; another value fails the start.- In code, the policy is
WebSocketClientConfig.reconnect, aWebSocketReconnectPolicy.
Message size limits
| Key | Default | Meaning |
|---|---|---|
spring.websocket.client.max-text-message-size |
8KB |
The largest text message a client reads, in UTF-8 bytes; a larger one closes the connection with 1009 (message too big) and ends the streams with a WebSocketException. -1 for no limit. |
spring.websocket.client.max-binary-message-size |
8KB |
The same for binary messages. |
8 KB is Tomcat's default in Spring; Tomcat counts characters for text. The browser has no limit.
Those two hold for every client of the application. One client gets limits of its own, so a server that sends large messages does not raise the limit of the others:
Key under spring.websocket.client.config.<name>. |
Default | Meaning |
|---|---|---|
max-text-message-size |
the client's default entry, then spring.websocket.client.max-text-message-size |
The largest text message this client reads. |
max-binary-message-size |
the client's default entry, then spring.websocket.client.max-binary-message-size |
The same for binary messages. |
# The feed sends JSON of up to 1 MB; every other client stays at 8 KB.
spring.websocket.client.config.feed.max-text-message-size=1MB
- A
@PhoenixChanneland aPhoenixSockettake them by their client name too. - The limits of a client are asked from the
WebSocketTransportat every connection (connect(url, maxTextMessageSize:, maxBinaryMessageSize:)), so they hold with a transport bean of your own as well. - In code they are
WebSocketClientConfig.maxTextMessageSizeandmaxBinaryMessageSize;nullkeeps the transport's own limits.
Handshake interceptors
A WebSocketHandshakeInterceptor bean changes the handshake of every connection and every reconnection before it is sent, so a token that expired in the meantime is replaced by a fresh one.
WebSocketHandshake member |
Meaning |
|---|---|
clientName |
The client's name, to act on some clients only. |
queryParameter(name, value) |
Adds a query parameter to the URL. |
headers |
The handshake headers (not in browsers). |
protocols |
The subprotocols offered. |
An interceptor that throws fails that connection attempt.
Flutter web and browsers cannot send headers with a WebSocket handshake; a header there fails with a WebSocketException. Put tokens in the URL (queryParameter) or in a subprotocol instead. The client's log lines and the messages of its exceptions show every query value and user information as *** (ws://chat.test/ws?token=***); the original error stays in the exception's cause.
For OAuth 2.0 tokens, including DPoP, OAuth2AccessTokenHeaders of spring_boot_starter_oauth2_client writes the headers (see spring_boot_starter_oauth2_client).
The transport
The webSocketTransport bean opens the connections. By default it is platformWebSocketTransport(): IoWebSocketTransport (dart:io) on the VM and in Flutter mobile and desktop, BrowserWebSocketTransport on the web. Declare your own WebSocketTransport bean to replace it, as tests do with a mock.
- On
dart:io, what a client sends waits in memory while the server does not take it. As Spring'sConcurrentWebSocketSessionDecoratordoes, the connection is dropped (4500) when more than 512 KB wait or what was sent has not left within 10 seconds; the client then reconnects. Declare anIoWebSocketTransport(sendBufferSizeLimit: ..., sendTimeLimit: ...)bean for other limits. - No extension is offered (no permessage-deflate). A handshake answer that picks a subprotocol the client did not offer, or any extension, fails the connection (RFC 6455).
- Redirects are not followed, as in browsers.
In Spring (Java)
Spring sets the limits in code, on the client's WebSocketContainer (setDefaultMaxTextMessageBufferSize), and has no client properties: spring.websocket.client.* and WebSocketHandshakeInterceptor are this project's own. The reconnect.* names follow Spring 7's RetryPolicy.