-
Notifications
You must be signed in to change notification settings - Fork 0
WebSocket Server
The WebSocket server that is in use, is the ws and the wrapper: express-ws.
The WebSocket support has two types for permissions, this is full
which allows WebSocket access to all controllers and all methods, or partial
which means for a controller and/or method to be allowed, you must enable WebSocket support in each controller and class, you can do this by adding true as the third argument to the @Controller()
or @Route()
decorators. In this example we will just use full access.
1. Enable WebSocket support.
The below we shall add the extra options to the application config, and then define the path, by default websocket is disabled and the default websocket path is: /ws
.
import { Framework } from 'rewyre';
import { PeopleController } from '../controller/people';
import { PeopleModel } from '../model/people';
import { LoggerProvider } from '../provider/logger';
import { ExampleService } from '../service/example';
(async () => {
const application: Framework = new Framework({
port: 8080,
websocket: true, // Enabled WebSocket, the default path and access is fine.
database: true,
databases: [
{
unique: 'main',
host: 'localhost',
port: 27017,
name: 'demo-rewyre-app',
driver: Drivers.MONGO,
default: true,
},
],
});
application.register([ PeopleController, PeopleModel, LoggerProvider, ExampleService ]);
await application.start();
});
2. Write some front-end code and test it.
The below is a very simple example to create a connection, we are assuming this is running on localhost and so is the code below. As you will see we use the namespace and the method instead to access controller methods, this is to make sure the router can find the right controller and route, and uses standard error checking.
const socket = new WebSocket('ws://localhost:8080/ws');
socket.addEventListener('open' (event) => {
console.log('Socket Connected', event);
socket.send(JSON.stringify({
command: 'people/index',
content: {},
}));
})
socket.addEventListener('close', (event) => { console.log('Connection Closed', event); });
socket.addEventListener('error', (event) => { console.log('Connection Error', event); });
socket.addEventListener('message', (event) => { console.log('Data From Socket', event); });
As part of 2.2.0 there was a new introduction for WebSockets called the WSHelper, which is a built-in inject, which is given to every module registered in the framework and offers some extra functionality for managing and working with WebSockets, see the function list below.
In any module do the following:
import { Controller, AbstractController, Route, IReturn, WSHelper } from 'rewyre';
@Controller('/hello', 'hello')
export class HelloController extends AbstractController {
public websocket!: WSHelper;
@Route('GET', '/')
public async index(): Promise<IReturn> {
this.websocket.broadcast('hello');
return { status: 200, content: 'Broadcasted message over all connected WS clients.' };
}
}
Function | Params | Description | Return |
---|---|---|---|
broadcast |
message: string, subscriptions?: Array |
Broadcasts a raw message as a string to all connected clients, optional subscriptions array can be given to broadcast to only specific connections with specific subscriptions. | boolean |
send |
id: string, message: string |
Sends a raw string to a specific client, ID is the sec-websocket-key . |
boolean |
createPacket |
command: string, content: any |
Creates a packet that can then be sent with the packet specific commands below, a packet is a way of structuring data, and is the same structure expected by the framework. | IPacket |
sendPacket |
id: string, packet: IPacket |
Sends an IPacket instance to a specific client, ID is the sec-websocket-key . |
boolean |
broadcastPacket |
packet: IPacket, subscriptions?: Array<string> |
Broadcasts an IPacket instance to all connected clients, optional subscriptions array can be given to broadcast to only specific connections with specific subscriptions. | boolean |
addSubscription |
id: string, subscription: string |
Adds a subscription to a client identified by the sec-websocket-key , a subscription is a simple string. |
boolean |
removeSubscription |
id: string, subscription: string |
Removes a subscription to a client identified by the sec-websocket-key , a subscription is a simple string. |
boolean |
hasSubscription |
id: string, subscription: string |
Checks if the user has a specific subscription, identified by sec-websocket-key . |
boolean |
getSubscriptions |
id: string |
Gets a list of all subscriptions a connection currently has assigned, identified by sec-websocket-key . |
Array |
setSessionItem |
id: string, key: string, value: any |
Sets a session key and value to an ID (sec-websocket-key ) for that user, all data is deleted on disconnect of the connection. |
boolean |
getSessionItem |
id: string, key: string |
Gets a session key and value to an ID (sec-websocket-key ) for that user, all data is deleted on disconnect of the connection. |
any |
hasSessionItem |
id: string, key: string |
Checks if a session key for a user by ID (sec-websocket-key ) exists, this is checked by not undefined. |
boolean |
getSessionKeys |
id: string |
Gets an array of session keys for the connection identified by sec-websocket-key . |
Array |