
# WebSocket

With `spring_boot_starter_websocket` in the dependencies too, the web server also accepts WebSocket connections on its port. The `server.websocket.*` properties limit the size of the messages a session reads and how much it may keep waiting to be sent.

## Why

A WebSocket stays open and carries messages both ways: a chat, live prices, a game, notifications. It needs the same server as the HTTP API, the same port, and the same filters (security in front of the handshake).

An open connection is also a risk. A client could send one huge message, or stop reading while the server keeps sending, until the server runs out of memory. The limits close such sessions early.

## Example

```yaml
# pubspec.yaml
dependencies:
  spring_boot_starter_web: ^0.9.0
  spring_boot_starter_websocket: ^0.9.0
```

```dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
import 'package:spring_boot_starter_websocket/spring_boot_starter_websocket.dart';

// ws://localhost:8080/ws/rooms/neon
@WebSocketEndpoint('/ws/rooms/{room}')
class ChatEndpoint {
  ChatEndpoint(this.sessions);
  final WebSocketSessionRegistry sessions;

  @OnMessage()
  Ack message(@PathVariable() String room, ChatMessage message) {
    sessions.broadcast('/ws/rooms/{room}', message); // to every open session
    return Ack(room: room, received: message.text);  // the reply, as JSON
  }
}

@Introspected()
class ChatMessage {
  const ChatMessage({required this.text});
  final String text;
}

@Introspected()
class Ack {
  const Ack({required this.room, required this.received});
  final String room;
  final String received;
}
```

```yaml
# lib/resources/application.yml
server:
  websocket:
    max-text-message-size: 64KB
    max-binary-message-size: 1MB
    send-buffer-size-limit: 1MB
    send-time-limit: 20s
```

```properties
server.websocket.max-text-message-size=64KB
server.websocket.max-binary-message-size=1MB
server.websocket.send-buffer-size-limit=1MB
server.websocket.send-time-limit=20s
```

`@WebSocketEndpoint`, `WebSocketHandler`, `WebSocketConfigurer`, handshake interceptors, origins and broadcasting belong to the WebSocket starter. Its README describes them: [spring_boot_starter_websocket, Server endpoints](https://github.com/farum-azula/spring_core_dart/blob/main/spring_boot_starter_websocket/README.md). This page covers what the web starter adds: the server side of the connection.

## Properties

| Key | Type | Default | Meaning |
|---|---|---|---|
| `server.websocket.max-text-message-size` | `DataSize` | `8KB` | The largest text message a session reads, in UTF-8 bytes. `-1`: no limit. |
| `server.websocket.max-binary-message-size` | `DataSize` | `8KB` | The largest binary message a session reads. `-1`: no limit. |
| `server.websocket.send-buffer-size-limit` | `DataSize` | `512KB` | The most a session may keep waiting to be sent. `-1`: no limit. |
| `server.websocket.send-time-limit` | `Duration` | `10s` | The longest what was sent may take to leave. `-1`: no limit. |

### `server.websocket.max-text-message-size`

- **Type:** `DataSize` (`8KB`, `64KB`, `1MB`; a plain number is bytes). **Default:** `8KB`, Tomcat's default in Spring. **`-1`:** no limit.
- **What it does:** a text message larger than this, counted in UTF-8 bytes, is not read. The session is closed with `1009` (message too big). The size is counted over all frames of the message, before the message is put together, so a message cut into many small frames cannot pass.
- **Log:** at `debug` level, under `spring.web.server`: `WebSocket session at /ws/rooms/neon closed with 1009: a message was larger than the limit`.
- **Why change it:** your messages are larger than 8 KB (a JSON document, a pasted text).
- **Example:** `server.websocket.max-text-message-size=64KB`.
- **Note:** Tomcat counts characters; this counts bytes. A text of 8,000 characters with accents or emoji can be more than 8 KB.

### `server.websocket.max-binary-message-size`

- **Type:** `DataSize`. **Default:** `8KB`. **`-1`:** no limit.
- **What it does:** the same limit for binary messages, in bytes. A larger one closes the session with `1009`.
- **Why change it:** clients send images, audio chunks, or files.
- **Example:** `server.websocket.max-binary-message-size=1MB`.

### `server.websocket.send-buffer-size-limit`

- **Type:** `DataSize`. **Default:** `512KB`. **`-1`:** no limit.
- **What it does:** what a session sends waits in memory until the client takes it. When more than this waits, the session gives up: the connection is dropped (a close frame could not get through either), and the session's close status is `4500` (`CloseStatus.sessionNotReliable`), with the reason. The handler's `afterConnectionClosed` (or `@OnClose`) gets it.
- **Pongs count too.** The pongs that answer the client's pings wait with the messages, so a client that sends pings and reads nothing reaches the limit as well.
- **Reading goes on.** While messages wait, the session still reads the client. A client that sends a lot while the server sends a lot too is not held up.
- **Log:** a warning under `spring.web.server`: `WebSocket session at /ws/rooms/neon dropped: <reason>`.
- **Why change it:** raise it when you send bursts larger than 512 KB that the network cannot take at once (a snapshot of a large state). Lower it to protect memory with many slow clients.
- **Example:** `server.websocket.send-buffer-size-limit=2MB`.

### `server.websocket.send-time-limit`

- **Type:** `Duration` (`10s`, `500ms`; a plain number is milliseconds). **Default:** `10s`. **`-1`:** no limit.
- **What it does:** when what a session sent has not left within this time, the connection is dropped the same way: close status `4500`.
- **Why change it:** raise it for clients on slow mobile networks; lower it to drop stuck clients sooner.
- **Example:** `server.websocket.send-time-limit=20s`.

### Sending at the client's pace

To send a lot without reaching the limits, wait until each message has left before the next one. The session of the web starter's server is an `IoWebSocketSession` (in a `@WebSocketEndpoint`, the `delegate` of the `DefaultServerWebSocketSession`). Its `flush()` completes when nothing waits in memory any more:

```dart
import 'package:spring_boot_starter_websocket/spring_boot_starter_websocket.dart';
import 'package:spring_web_dart/io.dart' show IoWebSocketSession;

Future<void> sendAll(ServerWebSocketSession session, Stream<String> lines) async {
  final raw = session is DefaultServerWebSocketSession ? session.delegate : session;
  await for (final line in lines) {
    session.sendMessage(line);
    if (raw is IoWebSocketSession) {
      await raw.flush(); // sent as fast as the client reads
    }
  }
}
```

`IoWebSocketSession` comes from `package:spring_web_dart/io.dart`: add `spring_web_dart` to your dependencies to import it.

`flush()` fails with a `WebSocketException` when the connection closes or is dropped first.

## The handshake

The handshake is an ordinary HTTP `GET` with `Connection: Upgrade` and `Upgrade: websocket`. So:

- **It passes the filters**: the security filter chain authenticates it like any other request, the forwarded headers are applied, the session filter runs.
- **It is checked by the server** (RFC 6455):

| Problem | Answer |
|---|---|
| no `Sec-WebSocket-Key`, two of them, or not 16 bytes in base64 | `400` |
| `Sec-WebSocket-Version` sent twice | `400` |
| a version other than `13`, or none | `426 Upgrade Required` with `Sec-WebSocket-Version: 13` |

- **It is answered** with `101 Switching Protocols`, without `Content-Length` or `Transfer-Encoding`.
- **It is not timed** by `server.request-timeout`.
- **With `server.ssl.client-auth=need`**, a handshake without a client certificate gets the 403 like any request.
- **The session's URI** has the scheme `ws`, or `wss` with TLS.

## Close codes

| Code | When |
|---|---|
| `1001` (going away) | the server stops: every open session is closed with the reason `Server stopping`, in both shutdown modes |
| `1006` (`CloseStatus.noCloseFrame`) | the client went away (a reset) while messages waited; the error is the reason. Also over TLS |
| `1009` (too big) | a message over `max-text-message-size` or `max-binary-message-size` |
| `4500` (`CloseStatus.sessionNotReliable`) | past `send-buffer-size-limit` or `send-time-limit` |
| your own | after `session.close(status)` from the server, the handler gets that status |

## Rules

- **No compression.** No extension is negotiated, so permessage-deflate is never used. `server.compression.*` does not apply.
- **One port.** WebSocket and HTTP share `server.port` (and TLS).
- **Shutdown.** Open sessions are closed at the start of a shutdown; a graceful stop does not wait for them. See [Shutdown](shutdown.md).
- **Order.** The WebSocket starter's handler mapping is asked after the controllers (order 1). See [Handler mappings](handler-mappings.md).
- **Tests.** `MockMvc.webSocket` opens an endpoint in memory. See [Testing](../testing.md).

## In Spring (Java)

```java
@Bean
ServletServerContainerFactoryBean createWebSocketContainer() {
  var container = new ServletServerContainerFactoryBean();
  container.setMaxTextMessageBufferSize(64 * 1024);
  container.setMaxBinaryMessageBufferSize(1024 * 1024);
  return container;
}

// and, per session:
new ConcurrentWebSocketSessionDecorator(session, 20_000, 1024 * 1024);
```

Differences that matter:

- The limits are properties (`server.websocket.*`, this starter's own keys). Spring sets them in code, on the container and on a session decorator.
- The text limit counts UTF-8 bytes; Tomcat counts characters.
- Every session has the send limits. In Spring, `ConcurrentWebSocketSessionDecorator` applies them only to STOMP sessions and to sessions you wrap. A plain handler on Tomcat blocks the sending thread instead (up to Tomcat's 20-second blocking send timeout). Await `flush()` to wait the same way.
- permessage-deflate is not offered; Tomcat negotiates it.

## See also

- [The embedded server](index.md)
- [Shutdown](shutdown.md)
- [Timeouts](timeouts.md)
- [Handler mappings](handler-mappings.md)
- [Filters](../filters.md)
- [Testing](../testing.md)
- [All properties](../properties.md)
- [Data sizes](../../spring-core-dart/conversion/data-size.md)
