Skip to main content

Connection

Manually manage the connection

The first time you access the realtime module, Altogic client library automatically establishes a connection to the realtime server and manages this connection for you. Most of the time you do not need to manually open or close a connection. However, if your use case requires closing the connection and then later opening it then you can use the open and close methods to manage your websocket connection.

tip

If you manually disconnect the connection, the socket will not try to reconnect.

// Manually open the websocket connection
altogic.realtime.open();

// Manually close the websocket connection
altogic.realtime.close();

Get websocket info

You can check whether the realtime connection has been establised successfully or not using the isConnected method and get the underlying websocket identifier using the getSocketId method.

// Check if the websocke is successfully connected to the realtime server. 
// Returns true if the realtime socket is connected otherwise false
if(altogic.realtime.isConnected())
console.log('Connected');

// Get the unique identifier of the underlying websocket connection
let socketId = altogic.realtime.getSocketId();

Listen to connection events

You can listen to key connection events through their respective listener functions. The following are the key connection events and their counterpart listener functions.

EventDescriptionListener function
ConnectFired upon successful connection to the realtime server.onConnect
DisconnectFired upon disconnection. The disconnection can happen due to forceful disconnection by the server, manual closing of the connection, or network problems etc.onDisconnect
Connect errorFired upon when an error occurs while establishing the websocket connection.onError
Reconnect attemptFired upon an attempt to reconnect.onReconnectAttempt
// Listen to Connect
altogic.realtime.onConnect(() => console.log('Connection established!'));

// Listen to Disconnect
altogic.realtime.onDisconnect((reason) => {
console.log(
'Disconnected due to',
reason,
altogic.realtime.getSocketId()
);
});

// Listen to Reconnect attempt
altogic.realtime.onReconnectAttempt((attemptNumber) =>
console.log('Reconnecting attempt#', attemptNumber)
);

// Listen to Connect error
altogic.realtime.onError((error) =>
console.log('Connection error', error, error.data)
);