# Socket.io

Socket.io enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed.

# Installation

Before using Socket.io, we need to install the Socket.io (opens new window) module.

npm install --save socket.io @types/socket.io @tsed/socketio
npm install --save-dev @tsed/socketio-testing
1
2

Then add the following configuration in your server Configuration:

import {Configuration} from "@tsed/di";
import "@tsed/platform-express";
import "@tsed/socketio"; // import socket.io Ts.ED module

@Configuration({
  socketIO: {
    // ... see configuration
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10

# Configuration

  • path: name of the path to capture (/socket.io).
  • serveClient: whether to serve the client files (true).
  • adapter: the adapter to use. Defaults to an instance of the Adapter that ships with Socket.io which is memory based. See socket.io-adapter (opens new window).
  • cors: Cors configuration.
  • parser: the parser to use. Defaults to an instance of the Parser that ships with Socket.io. See socket.io-parser (opens new window).

For more information see Socket.io documentation (opens new window)

# Socket Service

Socket.io allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. See namespace documentation (opens new window).

All Socket service work under a namespace, and you can create one Socket service per namespace.

Example:

import {IO, Nsp, Socket, SocketService, SocketSession, Reason} from "@tsed/socketio";
import * as SocketIO from "socket.io";

@SocketService("/my-namespace")
export class MySocketService {
  @Nsp nsp: SocketIO.Namespace;

  @Nsp("/my-other-namespace")
  nspOther: SocketIO.Namespace; // communication between two namespace

  constructor(@IO private io: SocketIO.Server) {}

  /**
   * Triggered the namespace is created
   */
  $onNamespaceInit(nsp: SocketIO.Namespace) {}

  /**
   * Triggered when a new client connects to the Namespace.
   */
  $onConnection(@Socket socket: SocketIO.Socket, @SocketSession session: SocketSession) {}

  /**
   * Triggered when a client disconnects from the Namespace.
   */
  $onDisconnect(@Socket socket: SocketIO.Socket, @Reason reason: string) {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

SocketService inherits from Service decorator, meaning a SocketService can be injected to another Service, Controller or Middleware.

Example:

import {Namespace, SocketService} from "@tsed/socketio";

@SocketService()
export class MySocketService {
  @Namespace nsp: Namespace;

  helloAll() {
    this.nsp.emit("hi", "everyone!");
  }
}
1
2
3
4
5
6
7
8
9
10

Then, you can inject your socket service into another Service, Controller, etc. as following:

import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {MySocketService} from "../services/MySocketService";

@Controller("/")
export class MyCtrl {
  constructor(private mySocketService: MySocketService) {}

  @Get("/allo")
  allo() {
    this.mySocketService.helloAll();

    return "is sent";
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Dynamic Namespaces

Socket.io dynamic namespaces (opens new window) can be implemented using SocketService , Namespace and Nsp

import {Nsp, SocketNsp, Input, SocketService} from "@tsed/socketio";
import * as SocketIO from "socket.io";

@SocketService(/my-namespace-.+/)
export class MySocketService {
  // This will be the parent namespace.
  @Nsp nsp: SocketIO.Namespace;

  @Input("eventName")
  async myMethod(@SocketNsp nsp: SocketNsp) {
    // nsp is the actual namespace of this call.
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# Declaring an Input Event

Input decorator declares a method as a new handler for a specific event.

import {Args, Input, Namespace, Socket, SocketService} from "@tsed/socketio";

@SocketService("/my-namespace")
export class MySocketService {
  @Input("eventName")
  myMethod(@Args(0) userName: string, @Socket socket: Socket, @Namespace nsp: Namespace) {
    console.log(userName);
  }
}
1
2
3
4
5
6
7
8
9

# Send a response

You have many choices to send a response to your client. Ts.ED offers some decorators to send a response:

socketio

Example:

import {Args, Emit, Input, Socket, SocketService} from "@tsed/socketio";

@SocketService("/my-namespace")
export class MySocketService {
  @Input("eventName")
  @Emit("responseEventName") // or Broadcast or BroadcastOthers
  async myMethod(@Args(0) userName: string, @Socket socket: Socket) {
    return "Message " + userName;
  }
}
1
2
3
4
5
6
7
8
9
10

TIP

All methods accept a promise as returned value. Ts.ED handles promise before returning a response to your consumer.

WARNING

Return value is only possible when the method is decorated by Emit , Broadcast and BroadcastOthers .

Since v7.59.0, you can omit the @Emit decorator. Ts.ED will automatically emit the returned value using the callback function given by Socket.io.

Example:

import {Args, Emit, Input, Socket, SocketService} from "@tsed/socketio";

@SocketService("/my-namespace")
export class MySocketService {
  @Input("eventName")
  async myMethod(@Args(0) userName: string) {
    return "Message " + userName;
  }
}
1
2
3
4
5
6
7
8
9

# Socket Session

Ts.ED creates a new session for each socket.

import {Args, Emit, Input, SocketService, SocketSession} from "@tsed/socketio";

@SocketService("/my-namespace")
export class MySocketService {
  @Input("eventName")
  @Emit("responseEventName") // or Broadcast or BroadcastOthers
  async myMethod(@Args(0) userName: string, @SocketSession session: SocketSession) {
    const user = session.get("user") || {};
    user.name = userName;

    session.set("user", user);

    return user;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

The session represents an arbitrary object that facilitates the storage of session data, allowing the sharing of information between Socket.IO servers.

In the event of an unexpected disconnection (i.e., when the socket is not manually disconnected using socket.disconnect()), the server will store the session of the socket. Upon reconnection, the server will make an attempt to restore the previous session.

To enable this behavior, you need to configure the Connection state recovery (opens new window) as follows:

import {Configuration} from "@tsed/di";
import "@tsed/platform-express";
import "@tsed/socketio";

@Configuration({
  socketIO: {
    // ... see configuration
    connectionStateRecovery: {
      // the backup duration of the sessions and the packets
      maxDisconnectionDuration: 2 * 60 * 1000,
      // whether to skip middlewares upon successful recovery
      skipMiddlewares: true
    }
  }
})
export class Server {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

TIP

By default, Ts.ED uses the built-in in-memory adapter for session management. However, for production environments, it is recommended to use the persistent adapters (opens new window) to enhance reliability.

# Middlewares

A middleware can also be used on a SocketService either on a class or on a method.

Here is an example of a middleware:

import {Args, SocketMiddleware} from "@tsed/socketio";
import {deserialize} from "@tsed/json-mapper";
import {User} from "../models/User";

@SocketMiddleware()
export class UserConverterSocketMiddleware {
  async use(@Args() args: any[]) {
    let [user] = args;
    // update Arguments
    user = deserialize(user, {type: User, useAlias: true});

    return [user];
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

TIP

The user instance will be forwarded to the next middleware and to your decorated method.

You can also declare a middleware to handle an error with SocketMiddlewareError . Here is an example:

import {Socket, SocketErr, SocketEventName, SocketMiddlewareError} from "@tsed/socketio";

@SocketMiddlewareError()
export class ErrorHandlerSocketMiddleware {
  async use(@SocketEventName eventName: string, @SocketErr err: any, @Socket socket: Socket) {
    console.error(err);
    socket.emit("error", {message: "An error has occured"});
  }
}
1
2
3
4
5
6
7
8
9

Two decorators are provided to attach your middleware on the right place:

Both decorators can be used as a class decorator or as a method decorator. The call sequence is the following for each event request:

Middlewares chain uses the Promise to run it. If one of this middlewares/method emits an error, the first middleware error will be called.

import {SocketService, SocketUseAfter, SocketUseBefore, Emit, Input, Args} from "@tsed/socketio";
import {UserConverterSocketMiddleware, ErrorHandlerSocketMiddleware} from "../middlewares";
import {User} from "../models/User";

@SocketService("/my-namespace")
@SocketUseBefore(UserConverterSocketMiddleware) // global version
@SocketUseAfter(ErrorHandlerSocketMiddleware)
export class MySocketService {
  @Input("eventName")
  @Emit("responseEventName") // or Broadcast or BroadcastOthers
  @SocketUseBefore(UserConverterSocketMiddleware)
  @SocketUseAfter(ErrorHandlerSocketMiddleware)
  async myMethod(@Args(0) user: User) {
    console.log(user);

    return user;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# Decorators

Loading in progress...

# Connecting the client

Once you have the socket set up on the server, you will want to connect up your client. Here are a few examples based on different configurations and namespaces.

# With default config

With this in your server configuration

@Configuration({
  socketIO: {} // uses all default values
})
1
2
3

And this in your service

import {IO, Nsp, Socket, SocketService, SocketSession} from "@tsed/socketio";
import * as SocketIO from "socket.io";

@SocketService("/my-socket-namespace")
export class MySocketService {
  @Nsp nsp: SocketIO.Namespace;

  // a map to keep clients by any id you like, a userId or whatever.
  public clients: Map<string, SocketIO.Socket> = new Map();

  constructor(@IO private io: SocketIO.Server) {}

  /**
   * Triggered when a new client connects to the Namespace.
   */
  $onConnection(@Socket socket: SocketIO.Socket, @SocketSession session: SocketSession) {
    console.log("=====   CONNECTED A CLIENT   =====");
    console.log(`===== SOCKET ID ${socket.id} =====`);

    this.clients.set(socket.id, socket);

    // if you pass in a query of some kind you could use an id passed from the front end
    // instead of the socket id, like this.
    const yourId: string | undefined = socket.handshake.query.yourId?.toString();
    if (yourId) this.clients.set(yourId, socket);
  }

  // setup a method to send data to all clients
  // you can use this from any other service or controller.
  broadcast(someData: any): void {
    this.nsp.emit("event_name", someData);
  }

  // method to send to a targeted client
  sendToSingleClient(idToSendTo: string, someData: any): void {
    const socket = this.clients.get(idToSendTo);
    if (!socket) return;
    socket.emit("eventName", someData);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

In plain javascript you could connect like this.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket Test</title>
    <script src="http://localhost:8083/socket.io/socket.io.js"></script>
</head>

<body>

</body>

<script>
    const socket = io("http://localhost:8083/my-socket-namespace?yourId=1234", { path: '/socket.io/my-socket-namespace/' });

    socket.on("connect", () => {
        console.log('connected to server');
    });

    // handle the event sent with socket.send()
    socket.on("disconnect", data => {
       console.log("disconnected")
    });

</script>

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# Testing v6.55.0+

    # Author

      # Maintainers Help wanted

        Last Updated: 10/24/2024, 6:33:40 AM

        Other topics