Test a WebSocket reconnect
Control when timers fire and how the socket replies. See how the same statechart reacts to each choice.
Try it
Drop the connection, then jump to the first retry at 2 seconds. Open the connection to cancel the 30-second deadline, or fail the attempt to queue another retry at 4 seconds.
The draft stays in the editor while the WebSocket reconnects. A simulated clock advances to each timer, and a stand-in socket waits for your reply.
The reconnect chart
This is the chart you just ran. Follow socket.closed from online to recovering, where the retry timer and the deadline start.
<?xml version="1.0" encoding="UTF-8"?>
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="connection" initial="online">
<state id="online">
<transition event="socket.closed" target="recovering"/>
</state>
<state id="recovering" initial="waiting">
<onentry><send id="grace" event="grace.elapsed" delay="30s"/></onentry>
<onexit><cancel sendid="grace"/></onexit>
<transition event="grace.elapsed" target="offline"/>
<state id="waiting">
<onentry><send id="backoff" event="retry.elapsed" delay="2s"/></onentry>
<onexit><cancel sendid="backoff"/></onexit>
<transition event="retry.elapsed" target="dialing"/>
</state>
<state id="dialing">
<onentry><send type="urn:socket" event="socket.open"/></onentry>
<transition event="socket.failed" target="waiting"/>
<transition event="socket.opened" target="online"/>
</state>
</state>
<state id="offline">
<transition event="retry.requested" target="recovering"/>
</state>
</scxml>The model is the system
Run the same connection.scxml in your browser client. The application uses the real clock and gives the host a socket handler that opens a real WebSocket when the chart asks.
const ioProcessors = { 'urn:socket': {
receive({ sender }) {
const next = new WebSocket(url);
socket = next;
let opened = false;
next.addEventListener('open', async () => {
if (socket !== next) return;
const { value } = await sender.state();
if (socket !== next) return;
if (value?.recovering !== 'dialing') {
socket = undefined;
next.close();
return;
}
opened = true;
sender.send('socket.opened');
onSocket(next);
});
next.addEventListener('close', () => {
if (socket !== next) return;
socket = undefined;
sender.send(opened ? 'socket.closed' : 'socket.failed');
});
},
} };The chart decides when to try again. The handler reports what happened and hands an open socket back to the application. Read the full client.