Socket.io
Rooms are the main feature that needs realtime communication. When you want to connect to a room you will use socket.io.
Connecting to a room
To connect to a room you have to be logged in and provide the given JWT when you want to connect to socket.io server.
When you connect to a room the server will emit user-connected event to users that are already connected to that room.
After a connection is established with the server, you will receive a initial-response event. This event will contain a list of users that
are connected to the room including yourself.
// Using socket.io client
// ES6 import
import {io} from "socket.io-client";
// CommonJS
const {io} = require("socket.io-client");
const socket = io('http://localhost:3000/rooms', {
extraHeaders: {
'room-code': '<Room code>',
'token': '<JWT>'
}
});
// Emiting events to server
socket.emit('message', "Hello from client");
// Handling events only when socket is connected
socket.on('connect', () => {
socket.on('user-connected', (message) => {
const user = message.data;
console.log(user.userID);
})
socket.on('initial-response', (message) => {
const users = message.data;
console.log(users);
})
});
// This is thrown afer trying to connect without success
socket.on('connect_error', () => {
console.log('Something happened when trying to connect to server');
});
// This is thrown after client disconnects from server, wheather the servers who disconnecs or the client.
socket.on('disconnect', (reason) => {
console.log('Client disconnected: ', reason);
});
// Using socket.io client
import {io, Socket} from "socket.io-client";
const socket: Socket = io('http://localhost:3000/rooms', {
extraHeaders: {
'room-code': '<Room code>',
'token': '<JWT>'
}
});
// Handling events only when socket is connected
socket.on('connect', () => {
socket.on('user-connected', (message) => {
const user = message.data;
console.log(user.userID);
})
socket.on('initial-response', (message) => {
const users = message.data;
console.log(users);
})
});
// This is thrown afer trying to connect without success
socket.on('connect_error', () => {
console.log('Something happened when trying to connect to server');
});
// This is thrown after client disconnects from server, wheather the servers who disconnecs or the client.
socket.on('disconnect', (reason) => {
console.log('Client disconnected: ', reason);
});
Even if you have a small application, it’s recommendable to have the socket instance centralized. With that you avoid to send socket between function calls and classes excessively. And simplifies managing the socket connection.