# 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 module.
npm install --save socket.io @types/socket.io
Then add the following configuration in your server Configuration:
import {Configuration} from "@tsed/common";
import "@tsed/platform-express";
import "@tsed/socketio"; // import socket.io Ts.ED module
@Configuration({
rootDir: __dirname,
socketIO: {
// ... see configuration
}
})
export class Server {
}
2
3
4
5
6
7
8
9
10
11
12
# Configuration
path
<string>: name of the path to capture (/socket.io).serveClient
<boolean>: whether to serve the client files (true).adapter
<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.origins
<string>: the allowed origins (*).parser
<Parser>: the parser to use. Defaults to an instance of the Parser that ships with Socket.io. See socket.io-parser.
For more information see Socket.io documentation
# 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.
All Socket service work under a namespace and you can create one Socket service per namespace.
Example:
import {IO, Nsp, Socket, SocketService, SocketSession} 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) {
}
}
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
inherits from 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!");
}
}
2
3
4
5
6
7
8
9
10
Then, you can inject your socket service into another Service, Controller, etc. as following:
import {Controller, Get} from "@tsed/common";
import {MySocketService} from "../services/MySocketService";
@Controller("/")
export class MyCtrl {
constructor(private mySocketService: MySocketService) {
}
@Get("/allo")
allo() {
this.mySocketService.helloAll();
return "is sent";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Declaring an Input Event
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);
}
}
2
3
4
5
6
7
8
9
- <any|any[]>: List of the parameters sent by the input event.
- <SocketIO.Socket>: Socket instance.
- <SocketIO.Namespace>: Namespace instance.
- <SocketIO.Namespace>: Namespace instance.
# Send a response
You have many choices to send a response to your client. Ts.ED offers some decorators to send a response:
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;
}
}
2
3
4
5
6
7
8
9
10
The method accepts a promise as returned value.
WARNING
Return value is only possible when the method is decorated by , and .
# 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;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Middlewares
A middleware can also be used on a either on a class or on a method.
Here is an example of a middleware:
import {ConverterService} from "@tsed/common";
import {Args, SocketMiddleware} from "@tsed/socketio";
import {User} from "../models/User";
@SocketMiddleware()
export class UserConverterSocketMiddleware {
constructor(private converterService: ConverterService) {
}
async use(@Args() args: any[]) {
let [user] = args;
// update Arguments
user = this.converterService.deserialize(user, User);
return [user];
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 . 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"});
}
}
2
3
4
5
6
7
8
9
Two decorators are provided to attach your middleware on the right place:
- will call your middleware before the class method,
- will call your middleware after the class method.
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 attached with on class,
- Middlewares attached with on method,
- The method,
- Send response if the method is decorated with , or ,
- Middlewares attached with on method,
- Middlewares attached with on class.
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;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Decorators
- Session & cookies
- Passport.js
- TypeORM
- Mongoose
- GraphQL
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Throw HTTP Exceptions
- Customize 404
- AWS
- Jest
- Seq
- Controllers
- Providers
- Model
- Converters
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Injection scopes
- Custom providers
- Custom endpoint decorator
- Testing