Note that there are two types of SCSocket objects - One which runs on the client and another which runs on the server. These two objects have slightly different APIs. This page concerns the client socket.
The client-side SCSocket object allows you to interact with your backend and with other client sockets in real-time. The SCSocket object uses WebSockets the underlying transport (since v2.0.0, there is no polling fallback).
One of the biggest differences between the client-side SCSocket and server-side SCSocket is that a client-side SCSocket is not ephemeral and will not be be discarded when it loses the connection - By default, it will try to reconnect automatically.
|id||The socket id.|
|state||The current state of the socket as a string - Can be socket.CONNECTING, socket.OPEN or socket.CLOSED.|
|pendingReconnect||A boolean which indicates if the socket is about to be automatically reconnected.|
|pendingReconnectTimeout||The number of milliseconds until the next reconnection attempt is executed.|
|connectAttempts||The number of automatic connect/reconnect attempts which the socket has executed (including the current latest attempt).|
|authState||The last known authentication state of the socket as a string. Can be either 'authenticated' (socket.AUTHENTICATED) or 'unauthenticated' (socket.UNAUTHENTICATED).|
|authToken||The auth token (as a plain Object) currently associated with the socket. This property will be null if no token is associated with this socket.|
|signedAuthToken||The signed auth token currently associated with the socket (encoded and signed in the JWT format). This property will be null if no token is associated with this socket.|
|channels||An object which holds all the channels (SCChannel object) attached to this socket (with the channel name as key). This object also contains channels which are in the 'unsubscribed' state.|
|CONNECTING||'connecting' - A string constant which represents this socket's connecting state. See state property.|
|OPEN||'open' - A string constant which represents this socket's open/connected state. See state property.|
|CLOSED||'closed' - A string constant which represents this socket's closed state. See state property.|
|AUTHENTICATED||'authenticated' - A string constant which represents this socket's authenticated authState.|
|UNAUTHENTICATED||'unauthenticated' - A string constant which represents this socket's unauthenticated authState.|
|'error'||This gets triggered when an error occurs on this socket. Argument is the error object.|
Emitted whenever the socket connects to the server (includes reconnections). The handler receives two arguments; the first is a status object in the form:
The second argument is a callback function (
|'disconnect'||Happens when this socket becomes disconnected from the server.|
|'connectAbort'||Triggers when a new connection is aborted for whatever reason - This could be caused by a failure during the connection phase or it may be triggered intentionally by calling socket.disconnect() while the socket is connecting.|
|'close'||Triggers when a socket is disconnected or the connection is aborted - This is a catch-all event for both
Triggers whenever the socket initiates a connection to the server - This includes reconnects.
In order capture the very first 'connecting' event, you will need to set the initial
|'raw'||This gets triggered whenever the server socket on the other side calls socket.send(...).|
|'kickOut'||Occurs when this socket is kicked out of a particular channel by the backend. Arguments are (message, channelName).|
|'subscribe'||When the subscription succeeds.|
|'subscribeFail'||Happens when the subscription fails. The first argument passed to the handler will be the error which caused the subscription to fail.|
|'unsubscribe'||When the socket becomes unsubscribed from a channel.|
Triggers whenever the client's authState changes between socket.AUTHENTICATED and socket.UNAUTHENTICATED states.
The handler will receive as an argument an object which has at least two properties:
|'authTokenChange' [Removed from socketcluster-client v12.0.0]||
This event was removed from socketcluster-client v12.0.0 onwards - The alternative is now to bind handlers to both the 'authenticate' and 'deauthenticate' events.
Triggers whenever the client's signedAuthToken and authToken properties are updated (including if the client is already authenticated).
The argument passed to the handler is the signedAuthToken. You can use
|'subscribeStateChange'||Triggers whenever a pub/sub channel's state transitions between 'pending', 'subscribed' and 'unsubscribed' states. The handler will receive as an argument an object which has three properties: channel, oldState and newState.|
|'subscribeRequest'||Emits the channel name when a `subscribe` action is invoked by the client.|
|'authenticate'||Triggers whenever the client is successfully authenticated by the server - The data argument passed along with this event is the base64 signed JWT auth token as a string.|
|'deauthenticate'||Triggers whenever the client becomes unauthenticated.|
|'message'||All data that arrives on this socket is emitted through this event as a string.|
For the list of all SC errors (and their properties) click here.
To check the type of an error in SC, you should use the
name property of the error (do not use the instanceof statement).
Errors which are sent to the client from the server will be dehydrated on the server and rehydrated on the client - As a result they will be cast
|connect()||Reconnects the client socket to its origin server.|
Returns the state of the socket as a string constant.
|getSignedAuthToken()||Returns the signed auth token as a string in the JWT format.|
|disconnect([code, data])||Disconnect this socket from the server. This function accepts two optional arguments: A custom error code (a Number - Ideally between 4100 to 4500) and data (which can be either reason message String or an Object).|
|emit(event, data, [callback])||
Emit the specified event on the corresponding server-side socket.
Note that you cannot emit any of the reserved SCSocket events.
This is the same as Socket.io's emit function except that if a callback is provided, your server-side socket will need to respond to this event - See example.
Also note that SC has a default timeout of 10 seconds for responding to events on the other side. You can increase this limit by setting
|on(event, handler)||Add a handler for a particular event (those emitted from a corresponding socket on the server). The handler is a function in the form: handler(data, res) - The res argument is a function which can be used to send a response to the server socket which emitted the event (assuming that the server is expecting a response - I.e. A callback was provided to the emit method). The res function is in the form: res(err, message) - To send back an error, you can do either: res('This is an error') or res(1234, 'This is the error message for error code 1234'). To send back a normal non-error response: res(null, 'This is a normal response message'). Note that both arguments provided to res can be of any JSON-compatible type.|
|off([event, handler])||Unbind a previously attached event handler.|
|send(data, [options]);||Send some raw data to the server. This will trigger a 'raw' event on the server which will carry the provided data.|
|authenticate(encryptedTokenString, [callback]);||Perform client-initiated authentication - This is useful if you already have a valid encrypted auth token string and would like to use it to authenticate directly with the server (without having to ask the user to login details). Typically, you should perform server-initiated authentication using the socket.setAuthToken() method from the server side. This method is useful if, for example, you received the token from a different browser tab via localStorage and you want to immediately authenticate the current socket without having to reconnect the socket. It may also be useful if you're getting the token from a third-party JWT-based system and you're using the same authKey (see boot options for SocketCluster) - In which case they should be compatible.|
|deauthenticate([callback]);||Perform client-initiated deauthentication - Deauthenticate (logout) the current socket. The callback will receive an error as the first argument if the operation fails.|
All of the following methods are related to pub/sub features of SC.
|publish(channelName, data, [callback])||Publish data to the specified channelName. The channelName argument must be a string. The data argument can be any JSON-compatible object/array or primitive. The callback lets you check that the publish action reached the backend successfully. Callback function is in the form callback(err, ackData) - On success, the err argument will be undefined. The ackData argument will be a value which is passed back from back end middleware (undefined by default); see the example about MIDDLEWARE_PUBLISH_IN for more details: Middleware and authorization.|
Subscribe to a particular channel.
This function returns an SCChannel object which lets you watch for incoming data on that channel.
Since v4.0.0, you can provide an optional options object in the form
|unsubscribe(channelName)||Unsubscribe from the specified channel. This makes any associated SCChannel object inactive. You can reactivate the SCChannel object by calling subscribe(channelName) again at a later time.|
|channel(channelName)||Returns an SCChannel instance. This is different from subscribe() in that it will not try to subscribe to that channel. The returned channel will be inactive initially. You can call channel.subscribe() later to activate that channel when required.|
|watch(channelName, handler)||Lets you watch a channel directly from the SCSocket object. The handler accepts a single data argument which holds the data which was published to the channel.|
|unwatch(channelName, [handler])||Stop handling data which is published on the specified channel. This is different from unsubscribe in that the socket will still receive channel data but the specified handler will no longer capture it. If the handler argument is not provided, all handlers for that channelName will be removed.|
|watchers(channelName)||Returns an array of listener functions which are watching for data on the specified channel.|
|destroyChannel(channelName)||This will cause SCSocket to unsubscribe that channel and remove any watchers from it. Any SCChannel object which is associated with that channelName will be disabled permanently (ready to be cleaned up by garbage collector).|
|subscriptions(includePending)||Returns an array of active channel subscriptions which this socket is bound to. If includePending is true, pending subscriptions will also be included in the list.|
|isSubscribed(channelName, [includePending])||Check if socket is subscribed to channelName. If includePending is true, pending subscriptions will also be included in the list.|
|destroy()||Disconnects and destroys the socket so that it can be garbage collected.|