Skip to content

Connecting and the Reconnect Policy

SamJakob edited this page Feb 4, 2021 · 2 revisions

Connecting and the Reconnect Policy

Connect to a server

// Instantiate the client.
var socket = SocketClusterClient(
  hostname: 'localhost',
  port: 3000,
  ackTimeout: 500,
);

// Connect to the server.
await socket.connect();

If you do not explicitly call .connect, the client will automatically connect when you call .transmit or .invoke, though it's recommended that you do call .connect explicitly so you can be sure the client has connected before you attempt to use it.

Additionally, if you use .send the data is directly passed to the socket stream so you'll need to make sure the socket has properly connected before you call it.

Detecting connection loss

When the socket is disconnected from the server either by the server or by the client, the SCEvent.DISCONNECT event is triggered (by the underlying dart:io WebSocket). You can subscribe to SCEvent.DISCONNECT with the .on method like so:

socket.on(SCEvent.DISCONNECT, () {
  print("Disconnected from server!");
});

The SCEvent.READY event is emitted when the client has successfully completed a handshake with the server both when the connection has been first established and when it is re-established:

socket.on(SCEvent.READY, () {
  print("Connected to the server!");
});

Auto-reconnecting to the server

Croupier supports auto-reconnecting to the server if it has not been explicitly disconnected by means of a ReconnectPolicy.