In this section we will get to know the client APIs.
We connect to a socket using the connect
method on the io
object in the client:
var socket = io.connect(<uri>);
Here, uri
is the server URI to connect to. It can be absolute or relative. If it is other than /
, or an absolute equivalent of that, it will connect to the namespace.
We can attach event handlers to a socket using the on
method:
socket.on(<event>, function(event_data, ack_callback){});
Here, event
is the event to listen for, event_data
is the data for the event, and ack_callback
is the optional callback method to call to acknowledge the receipt of the event.
We use the emit
method to trigger an event. This event will be handled on the server:
socket.on(<event>, <event_data>, ack_callback);
Here, event
is the name of the event to trigger, event_data
is the event data as a JSON object, and ack_callback
is the optional callback function that is invoked on the successful receipt of the message on the server.