Skip to content

Commit 9ab4fbf

Browse files
author
Deepak Kumar
committed
Enhanced STOMP.js documentation with examples for forceful deactivation, custom WebSocket usage (e.g., SockJS), receipt handling, heartbeat strategy, connection timeout, and advanced options.
1 parent c0bca86 commit 9ab4fbf

File tree

1 file changed

+78
-12
lines changed

1 file changed

+78
-12
lines changed

_posts/2018-06-29-using-stompjs-v5.md

Lines changed: 78 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,28 @@ To deactivate a client, call [Client#deactivate](/api-docs/latest/classes/Client
117117
await client.deactivate();
118118
```
119119

120+
You can also request an immediate teardown by passing `{ force: true }`. This skips both STOMP and WebSocket shutdown sequences and is useful if the underlying socket is stale and the browser is slow to close it.
121+
122+
```javascript
123+
// Forceful, immediate shutdown (skips STOMP and WebSocket close sequences)
124+
await client.deactivate({ force: true });
125+
```
126+
127+
### Use a custom WebSocket (e.g., SockJS)
128+
129+
Instead of `brokerURL`, you may supply a factory that returns a WebSocket-like object. If both `webSocketFactory` and `brokerURL` are set, `webSocketFactory` is used.
130+
131+
```javascript
132+
import { Client } from '@stomp/stompjs';
133+
import SockJS from 'sockjs-client';
134+
135+
const client = new Client({
136+
webSocketFactory: () => new SockJS('http://localhost:15674/stomp'),
137+
});
138+
139+
client.activate();
140+
```
141+
120142
## Send messages
121143

122144
When the client is connected, it can send STOMP messages using the [Client#publish](/api-docs/latest/classes/Client.html#publish) method.
@@ -215,7 +237,7 @@ See [Send messages](#send-messages) for an example.
215237

216238
### Receiving binary messages
217239

218-
The library does not infer whether incoming data is text or binary. Use [Message#body](/api-docs/latest/interfaces/IFrame.html#body) to access the body as a string, or [Message#binaryBody](/api-docs/latest/interfaces/IFrame.html#binaryBody) to access it as binary.
240+
The library does not infer whether incoming data is text or binary. Use [Message#body](/api-docs/latest/interfaces/IMessage.html#body) to access the body as a string, or [Message#binaryBody](/api-docs/latest/interfaces/IMessage.html#binaryBody) to access it as binary.
219241

220242
There is no generally accepted convention in STOMP (or messaging in general) to indicate binary messages. Producers and consumers should agree on a convention—for example, set a `content-type` header to indicate a binary payload.
221243

@@ -317,6 +339,32 @@ client.publish({
317339
tx.abort(); // Too late! the message has been sent
318340
```
319341

342+
## Receipts
343+
344+
Some operations (SUBSCRIBE, SEND, BEGIN/COMMIT/ABORT, DISCONNECT) can be acknowledged by the broker via RECEIPT frames when you include a unique `receipt` header. Use [Client#watchForReceipt](/api-docs/latest/classes/Client.html#watchForReceipt) to be notified when a given receipt arrives.
345+
346+
```javascript
347+
// Watch for a subscription receipt
348+
const subReceipt = 'sub-' + crypto.randomUUID();
349+
client.watchForReceipt(subReceipt, (frame) => {
350+
console.log('Subscribed, receipt:', frame.headers['receipt-id']);
351+
});
352+
client.subscribe('/queue/test', onMessage, { receipt: subReceipt });
353+
354+
// Watch for a publish receipt
355+
const sendReceipt = 'send-' + crypto.randomUUID();
356+
client.watchForReceipt(sendReceipt, () => {
357+
console.log('Message accepted by the broker.');
358+
});
359+
client.publish({
360+
destination: '/topic/general',
361+
body: 'Hello',
362+
headers: { receipt: sendReceipt },
363+
});
364+
```
365+
366+
If no watcher is active for an arriving receipt, [Client#onUnhandledReceipt](/api-docs/latest/classes/Client.html#onUnhandledReceipt) will be invoked.
367+
320368
## Heart-beating
321369

322370
For STOMP 1.1 or higher, heart-beating is enabled by default. Options [Client#heartbeatIncoming](/api-docs/latest/classes/Client.html#heartbeatIncoming) and [Client#heartbeatOutgoing](/api-docs/latest/classes/Client.html#heartbeatOutgoing) control heart-beating (default 10,000 ms). Set either to 0 to disable.
@@ -328,6 +376,15 @@ client.heartbeatIncoming = 0; // client does not want to receive heartbeats from
328376

329377
Very small heartbeat intervals can increase server load; tune with care in production.
330378

379+
### Heartbeat strategy
380+
381+
Control the scheduling strategy used for outgoing heartbeats with [Client#heartbeatStrategy](/api-docs/latest/classes/Client.html#heartbeatStrategy). Use `'interval'` (default) or `'worker'` (uses Web Workers when available). Using `'worker'` may improve reliability when the page is in a background tab, where browsers often throttle or pause timers.
382+
383+
```javascript
384+
import { TickerStrategy } from '@stomp/stompjs';
385+
client.heartbeatStrategy = TickerStrategy.Worker; // or TickerStrategy.Interval
386+
```
387+
331388
## Auto Reconnect
332389

333390
The client supports automatic reconnection after a connection failure. It is controlled by the [Client#reconnectDelay](/api-docs/latest/classes/Client.html#reconnectDelay) option. The default is 5000 ms, meaning the client will attempt to reconnect 5 seconds after a drop.
@@ -352,7 +409,15 @@ client.configure({
352409
});
353410
```
354411

355-
For UMD usage in the browser, use `StompJs.ReconnectionTimeMode.EXPONENTIAL`.
412+
When using exponential backoff, [Client#maxReconnectDelay](/api-docs/latest/classes/Client.html#maxReconnectDelay) caps the wait time (default 15 minutes). Set it to 0 to disable the cap.
413+
414+
### Connection timeout
415+
416+
Use [Client#connectionTimeout](/api-docs/latest/classes/Client.html#connectionTimeout) to fail-fast if a connection is not established in time. When the timeout elapses without connecting, the underlying socket is closed and a reconnect is scheduled (if enabled).
417+
418+
```javascript
419+
client.connectionTimeout = 8000; // close and retry if not connected within 8 seconds
420+
```
356421

357422
## Debug
358423

@@ -377,27 +442,28 @@ Usually, headers of incoming and outgoing frames are logged. Set [Client#logRawC
377442
- [Client#onDisconnect](/api-docs/latest/classes/Client.html#onDisconnect) — invoked after each graceful disconnection. If the connection breaks due to an error or network failure, it is not called.
378443
- [Client#onStompError](/api-docs/latest/classes/Client.html#onStompError) — invoked when the broker reports an error.
379444
- [Client#onWebSocketClose](/api-docs/latest/classes/Client.html#onWebSocketClose) — invoked when the WebSocket closes. This is the most reliable way to detect that the connection terminated.
445+
- [Client#onWebSocketError](/api-docs/latest/classes/Client.html#onWebSocketError) — invoked when the underlying WebSocket raises an error event.
380446

381447
### Frame callbacks
382448

383449
- [Client#onUnhandledMessage](/api-docs/latest/classes/Client.html#onUnhandledMessage) — typically, brokers send messages corresponding to subscriptions. However, some brokers support concepts beyond standard STOMP (for example, RabbitMQ temporary queues). This callback is invoked if a message is received that is not linked to a subscription.
384450
- [Client#onUnhandledReceipt](/api-docs/latest/classes/Client.html#onUnhandledReceipt) — prefer [Client#watchForReceipt](/api-docs/latest/classes/Client.html#watchForReceipt). If a receipt arrives with no active watcher, this callback is invoked.
385451
- [Client#onUnhandledFrame](/api-docs/latest/classes/Client.html#onUnhandledFrame) — invoked if the broker sends a non-standard STOMP frame.
386452

387-
## Advanced notes
388-
389-
Version 5+ of this library differs significantly from earlier versions.
390-
391-
You can change configuration options and callbacks at runtime. New values take effect as soon as possible. For example:
453+
### State changes
392454

393-
- Updated values of [Client#onUnhandledMessage](/api-docs/latest/classes/Client.html#onUnhandledMessage) or [Client#onDisconnect](/api-docs/latest/classes/Client.html#onDisconnect) are effective immediately.
394-
- New values of [Client#heartbeatIncoming](/api-docs/latest/classes/Client.html#heartbeatIncoming) and [Client#heartbeatOutgoing](/api-docs/latest/classes/Client.html#heartbeatOutgoing) are used on the next STOMP connect.
455+
- [Client#onChangeState](/api-docs/latest/classes/Client.html#onChangeState) — invoked whenever the client's activation state changes.
456+
- [Client#state](/api-docs/latest/classes/Client.html#state) reflects the current activation state; [Client#active](/api-docs/latest/classes/Client.html#active) is `true` when connecting/connected or scheduled to reconnect.
395457

396-
Callback sequences are designed so that common operations work as expected. For example, you can call [Client#deactivate](/api-docs/latest/classes/Client.html#deactivate) within [Client#onStompError](/api-docs/latest/classes/Client.html#onStompError) or [Client#onWebSocketClose](/api-docs/latest/classes/Client.html#onWebSocketClose).
458+
## Advanced options
397459

398-
You can also adjust [Client#reconnectDelay](/api-docs/latest/classes/Client.html#reconnectDelay) in [Client#onWebSocketClose](/api-docs/latest/classes/Client.html#onWebSocketClose) to implement exponential backoff by progressively increasing the delay.
460+
These options are rarely needed; use only when you understand broker and environment behavior:
399461

400-
Even [Client#brokerURL](/api-docs/latest/classes/Client.html#brokerURL) and [Client#connectHeaders](/api-docs/latest/classes/Client.html#connectHeaders) can be altered; the new values will be used on the next reconnect.
462+
- [Client#splitLargeFrames](/api-docs/latest/classes/Client.html#splitLargeFrames) and [Client#maxWebSocketChunkSize](/api-docs/latest/classes/Client.html#maxWebSocketChunkSize): split large text frames into chunks (some non-standard brokers require this; compliant brokers do not).
463+
- [Client#forceBinaryWSFrames](/api-docs/latest/classes/Client.html#forceBinaryWSFrames): force binary WebSocket frames instead of letting the browser decide.
464+
- [Client#appendMissingNULLonIncoming](/api-docs/latest/classes/Client.html#appendMissingNULLonIncoming): workaround for a React Native bug that can drop trailing NULLs.
465+
- [Client#logRawCommunication](/api-docs/latest/classes/Client.html#logRawCommunication): log complete frames instead of just headers. Caution: assumes valid UTF-8.
466+
- [Client#discardWebsocketOnCommFailure](/api-docs/latest/classes/Client.html#discardWebsocketOnCommFailure): aggressively discard sockets on heartbeat failures to speed up recovery on some platforms.
401467

402468
[Polyfills]: {% link _posts/2018-06-28-polyfills-for-stompjs.md %}
403469
[Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array

0 commit comments

Comments
 (0)