Skip to content

Socket.IO Client Integration Guide

Overview

This guide provides a comprehensive set of instructions for integrating a client application with the Hubtel Realtime Socket.IO server. It includes how to connect to the server, handle various events, emit messages, and manage connection errors.

Prerequisites

To integrate your dotnet client application with the Hubtel Realtime Socket.IO server, you need to have the following:

Install the library using:

bash
<PackageReference Include="SocketIOClient" Version="3.1.2" />

Server URL: Know the URL for the Socket.IO server

CORS Configuration: CORS Configuration: Ensure the server allows connections from your client’s domain. Contact the product SRE team for assistance with CORS configuration.

Connecting to the Server

Basic Connection

Use socket.io-client to establish a connection to the Socket.IO server. Replace 'https://your-server-address:port' with the actual server URL.

csharp
var client = new SocketIO("http://localhost:11000/");

client.On("hi", response =>
{
    // You can print the returned data first to decide what to do next.
    // output: ["hi client"]
    Console.WriteLine(response);

    string text = response.GetValue<string>();

    // The socket.io server code looks like this:
    // socket.emit('hi', 'hi client');
});

client.On("test", response =>
{
    // You can print the returned data first to decide what to do next.
    // output: ["ok",{"id":1,"name":"tom"}]
    Console.WriteLine(response);
    
    // Get the first data in the response
    string text = response.GetValue<string>();
    // Get the second data in the response
    var dto = response.GetValue<TestDTO>(1);

    // The socket.io server code looks like this:
    // socket.emit('hi', 'ok', { id: 1, name: 'tom'});
});

client.OnConnected += async (sender, e) =>
{
    // Emit a string
    await client.EmitAsync("hi", "socket.io");

    // Emit a string and an object
    var dto = new TestDTO { Id = 123, Name = "bob" };
    await client.EmitAsync("register", "source", dto);
};
await client.ConnectAsync();

Channel

A channel is a communication pathway in the Socket.io server that allows for real-time data exchange between the client and server, ensuring all connected clients receive broadcasted messages.

See it as a public communication line where everyone can listen in, ensuring that all participants have access to general updates and information, promoting broad communication.

All messages sent and received from a channel are broadcasted to all connected clients, formatted as objects with a specific structure.

How To Join A Channel

To join a channel, the client emits a join-channel event to the server. The server then adds the client to the channel.

csharp

 var socketMessage = new ChatPayload()
 {
     Data = new ChatData()
     {
         Message = message,
         RoomChannel = "some-channel-id"
     },
     Time = DateTime.Now,
     ClientId = _client.Id,
     Source = new Source()
     {
         Platform = "Web",
         AppName = "NRTC web api",
         AppVersion = "1.0",
         ClientId = _client.Id,
         UserName = "NRTC",
         Channel = "some-channel-id"
     }
 };

 await _client.EmitAsync("join-channel", JsonSerializer.Serialize(socketMessage), channelName);

The above code adds the user to the channel with the ID some-channel-id. A typical use case is when two or more users need to communicate with each other in a group chat or discussion forum. In such case, the users join the same channel: some-channel-id to receive messages from other participants.

Send Message to a channel

To send a message to a channel, the client emits to the channel Id with the message payload. The server then broadcasts the message to all connected clients in the channel.

csharp
var socketMessage = new ChatPayload()
{
    Data = new ChatData()
    {
        Message = message,
        RoomChannel = "channelId"
    },
    Time = DateTime.Now,
    ClientId = _client.Id,
    Source = new Source()
    {
        Platform = "Web",
        AppName = "NRTC web api",
        AppVersion = "1.0",
        ClientId = _client.Id,
        UserName = "NRTC",
        Channel = "channelId"
    }
};
await _client.EmitAsync("channelId", JsonSerializer.Serialize(socketMessage), channelName);

The above code sends a message to the channel with the ID channelId. The message is broadcasted to all connected clients in the channel.

Leave A Channel

When a client is no longer interested in receiving messages from a channel, it can leave the channel by emitting a leave-channel event to the server. The server then removes the client from the channel.

csharp
 var socketMessage = new ChatPayload()
 {
     Data = new ChatData()
     {
         Message = message,
         RoomChannel = channelName
     },
     Time = DateTime.Now,
     ClientId = _client.Id,
     Source = new Source()
     {
         Platform = "Web",
         AppName = "NRTC web api",
         AppVersion = "1.0",
         ClientId = _client.Id,
         UserName = "NRTC",
         Channel = channelName
     }
 };

await _client.EmitAsync("leave-channel", JsonSerializer.Serialize(socketMessage), channelName);

Other Sever Events for Channels

The server emits certain events to the clients in a channel. The client can listen to these events using the on method.

Event NameDescription
online-usersSent by the server to provide data on the number of online users across channels.
join-channelSent by the server when a new user join a specific channel.
leave-channelSent by the server when a new user leave a specific channel.

See example below:

csharp

        _client.On("online-users", response =>
        {
            logger.LogInformation("Online users " + response);
        });

Room

A room is a sub-division within a channel that allows grouping of clients. It enables targeted message delivery to specific clients, facilitating private and efficient communication within the broader channel.

A room within that channel is like a private discussion group where only selected participants can join, enabling focused, private conversations and ensuring that relevant information is shared only with those who need it.

Join A Room

To join a room, the client emits a join-room event to the server. A client can join a room in a channel.

csharp
 var socketMessage = new ChatPayload()
 {
     Data = new ChatData()
     {
         Message = message,
         Room = roomName
     },
     Time = DateTime.Now,
     ClientId = _client.Id,
     Source = new Source()
     {
         Platform = "Web",
         AppName = "NRTC web api",
         AppVersion = "1.0",
         ClientId = _client.Id,
         UserName = "NRTC",
         Room = roomName
     }
 };

await _client.EmitAsync("join-room", JsonSerializer.Serialize(socketMessage), roomName);

Send Message to a Room

To send a message to a room, the client emits a notify-room event to the server. The server then broadcasts the message to all connected clients in the room.

csharp
 var socketMessage = new ChatPayload()
 {
     Data = new ChatData()
     {
         Message = message,
         Room = roomName
     },
     Time = DateTime.Now,
     ClientId = _client.Id,
     Source = new Source()
     {
         Platform = "Web",
         AppName = "NRTC web api",
         AppVersion = "1.0",
         ClientId = _client.Id,
         UserName = "NRTC",
         Room = roomName
     }
 };

await _client.EmitAsync("notify-room", JsonSerializer.Serialize(socketMessage), roomName);

Leave A Room

When a client is no longer interested in receiving messages from a room, it can leave the room by emitting a leave-room event to the server. The server then removes the client from the room.

csharp
 var socketMessage = new ChatPayload()
 {
     Data = new ChatData()
     {
         Message = message,
         Room = roomName
     },
     Time = DateTime.Now,
     ClientId = _client.Id,
     Source = new Source()
     {
         Platform = "Web",
         AppName = "NRTC web api",
         AppVersion = "1.0",
         ClientId = _client.Id,
         UserName = "NRTC",
         Room = roomName
     }
 };

await _client.EmitAsync("leave-room", JsonSerializer.Serialize(socketMessage));

Other Sever Events for Rooms

The server emits certain events to the clients in a particular which be useful.

Event NameDescription
room-online-usersSent by the server to provide data on the number of online users in a specific room. The event is emitted whe a new user joins the room
join-roomEmitted when a new user join a specific room.
leave-roomEmitted when a new user leave a specific room.

Request Payload

The request payload is the data structure that the client sends to the server when emitting an event. The payload contains the message, room ID, room channel, time, client ID, and source information. Create your own c# class based on the properties below:

FieldDescription
dataAn object containing information about the message
data.messageThe message to be sent to the server. If the event does not require a message, pass an empty string
data.roomIdThe ID of the room to which the message belongs. Pass null for channel communication
data.roomChannelThe ID of the channel to which the room belongs.
timeThe timestamp of the message.
clientIdThe ID of the client sending the message.
sourceInformation about the source of the message, including platform and app details.
source.platformThe platform from which the message is sent (e.g., web, mobile).
source.appNameThe name of the application sending the message.
source.appVersionThe version of the application sending the message.
source.clientIdThe ID of the client sending the message.
source.userNameThe name of the user sending the message.
source.channelThe id of the channel the message is sent from

For more info about the c# library used 'https://github.com/doghappy/socket.io-client-csharp'