
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
@tsed/socketio
Advanced tools
Experimental feature. You can contribute to improve this feature !
A package of Ts.ED framework. See website: https://romakita.github.io/ts-express-decorators/#/tutorials/socket-io
Socket.io enable real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed.
Before using the Socket.io, we need to install the Socket.io module.
npm install --save socket.io @types/socket.io @tsed/socketio
Then add the following configuration in your ServerLoader:
import {ServerLoader, ServerSettings} from "@tsed/common";
import "@tsed/socketio"; // import socketio Ts.ED module
import Path = require("path");
const rootDir = Path.resolve(__dirname)
@ServerSettings({
rootDir,
socketIO: {
// ... see configuration
}
})
export class Server extends ServerLoader {
}
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 * as SocketIO from "socket.io";
import {SocketService, IO, Nsp, Socket, SocketSession} from "@tsed/socketio";
@SocketService("/my-namespace")
export class MySocketService {
@Nsp nsp: SocketIO.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) {
}
}
@SocketService inherit from @Service decorator. That means, a SocketService can be injected to another Service, Controller or Middleware.
Example:
import * as SocketIO from "socket.io";
import {SocketService, Nsp} from "@tsed/socketio";
@SocketService()
export class MySocketService {
@Nsp nsp: SocketIO.Namespace;
helloAll() {
this.nsp.emit('hi', 'everyone!');
}
}
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";
}
}
@Input decorator declare a method as a new handler for a specific event
.
import {SocketService, Input, Emit, Args, Socket, Nsp} from "@tsed/socketio";
@SocketService("/my-namespace")
export class MySocketService {
@Input("eventName")
myMethod(@Args(0) userName: string, @Socket socket: SocketIO.Socket, @Nsp nsp: SocketIO.Namespace) {
console.log(userName);
}
}
You have a many choice to send a response to your client. Ts.ED offer some decorators to send a response:
Example:
import {SocketService, Input, Emit, Args, Socket, Nsp} 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: SocketIO.Socket) {
return "Message " + userName;
}
}
The method accept a promise as returned value.
!> Return value is only possible when the method is decorated by @Emit, @Broadcast and @BroadcastOthers.
Ts.ED create a new session for each socket.
import {SocketService, Input, Emit, Args, 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;
}
}
A middleware can be also used on a SocketService
either on a class or on a method.
Here an example of a middleware:
import {ConverterService} from "@tsed/common";
import {SocketMiddleware, Args} 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 = ConverterService.deserialize(user, User);
return [user];
}
}
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 an example:
import {SocketMiddleware, Args} from "@tsed/socketio";
@SocketMiddlewareError()
export class ErrorHandlerSocketMiddleware {
async use(@SocketErr err: any, @Socket socket: SocketIO.Socket) {
console.error(err);
socket.emit("error", {message: "An error has occured"})
}
}
Then, two decorators are provided to attach your middleware on the right place:
@SocketUseBefore
will call your middleware before the class method,@SocketUseAfter
will call your middleware after the class method.Both decorators can be used as a class decorator or as a method decorator. The call sequences is the following for each event request:
@SocketUseBefore
on class,@SocketUseBefore
on method,@Emit
, @Broadcast
or @BroadcastOther
,@SocketUseAfter
on method,@SocketUseAfter
on class.Middlewares chain use the Promise
to run it. If one of this middlewares/method emit an error, the first middleware error will be called.
import {SocketService, SocketUseAfter, SocketUseBefore, Emit, Input, Args, SocketSession} 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) userName: User) {
const user = session.get("user") || {}
user.name = userName;
session.set("user", user);
return user;
}
}
See our documentation https://romakita.github.io/ts-express-decorators/#/api/index
Please read contributing guidelines here.
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
The MIT License (MIT)
Copyright (c) 2016 - 2018 Romain Lenzotti
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Socket.io package for Ts.ED framework
The npm package @tsed/socketio receives a total of 1,055 weekly downloads. As such, @tsed/socketio popularity was classified as popular.
We found that @tsed/socketio demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.