@@ -26,6 +26,10 @@ const delegate = {
2626 },
2727 socketDidReceiveMessage(socket : Socket , message : string ) {
2828 // Socket read data from the connection.
29+ },
30+ socketShouldRetry(socket : Socket , code : number ): boolean {
31+ // Socket reconnects unless server returns the policy violation code.
32+ return code !== 1008
2933 }
3034}
3135
@@ -35,8 +39,65 @@ const policy = {
3539 maxDelay: 60000
3640}
3741
38- const socket = new StableSocket (' wss://live.example.com' , delegate , policy )
42+ const url ' wss://live.example.com'
43+ const socket = new StableSocket (url , delegate , policy )
44+ socket .open ()
45+ ```
46+
47+ ### BufferedSocket
48+
49+ Writing to a StableSocket while it is in the opening or closed states
50+ discards the message data. Use a BufferedSocket to buffer writes to be
51+ sent when it opens.
52+
53+ ``` ts
54+ import {BufferedSocket , StableSocket } from ' @github/stable-socket'
55+ const socket = new BufferedSocket (new StableSocket (url , delegate , policy ))
3956socket .open ()
57+ socket .send (' hello' ) // Will be sent when the socket is open.
58+ ```
59+
60+ ### Asynchronous connections
61+
62+ StableSocket and BufferedSocket are abstractions over a WebSocket that
63+ maintain an internal state machine, managing reconnects and preventing writes
64+ to closed sockets. However, sometimes we need direct access to an open WebSocket
65+ in async functions.
66+
67+ #### connect
68+
69+ Asynchronously connects to a web socket port or fails after a timeout. The
70+ socket is open, and writable with ` send ` , when its promise is fulfilled.
71+ Returns a Promise fulfilled with an open WebSocket or rejected with a
72+ connection failure.
73+
74+ ``` ts
75+ import {connect } from ' @github/stable-socket'
76+
77+ try {
78+ const socket = await connect (' wss://live.example.com' , 100 )
79+ socket .send (' hi' )
80+ } catch (e ) {
81+ console .log (' Socket connection failed' , e )
82+ }
83+ ```
84+
85+ #### connectWithRetry
86+
87+ Asynchronously connects to a web socket port, retrying failed connections
88+ with exponential backoff. Returns a Promise fulfilled with an open WebSocket
89+ or rejected with a connection failure.
90+
91+ ``` ts
92+ import {connectWithRetry } from ' @github/stable-socket'
93+
94+ try {
95+ const policy = {timeout: 100 , attempts: Infinity , maxDelay: 60000 }
96+ const socket = await connectWithRetry (' wss://live.example.com' , policy )
97+ socket .send (' hi' )
98+ } catch (e ) {
99+ console .log (' Socket connection failed' , e )
100+ }
40101```
41102
42103## Development
0 commit comments