websocket-server-wrapper
v1.0.4
Published
A WebSocket server implementation with TypeScript support
Readme
WebSocket Server
A TypeScript implementation of a WebSocket server with additional features.
Installation
npm install websocket-server-wrapperUsage
import { WsServer, WebsocketServer, SocketConnection, WsNextFunc } from 'websocket-server-wrapper';
import http from 'http';
import express from 'express';
const app = express();
const httpServer = http.createServer(app);
class MyError extends Error {
#code: number;
constructor(message: string, code?: number) {
super(message);
this.name = "MyError";
this.#code = code || 500;
}
get code() {
return this.#code;
}
}
// Create a new WebSocket server
const wsServer = new WsServer({
noServer: true,
// Add your configuration here
});
// Attach the WebSocket server to the HTTP server
wsServer.attachServer(httpServer);
wsServer.setAuth((req: http.IncomingMessage) => {
// Handle authorization
const token = req.headers.authorization?.split(' ')[1];
if(!token){
return false;
}
return true;
});
const validateRoomId = (data: {room_id?: string, message?: string}, next: WsNextFunc) => {
if(!data?.room_id){
throw new MyError("Room id is required", 400)
}
if(!wsServer.isExistRoom(data.room_id)){
throw new MyError("Room not found", 404)
}
next()
}
// Set event handler
wsServer.connected({
connectionHandler: (ws: SocketConnection, wss: WebsocketServer) => {
const query = ws.getQuery()
const user_id = query.user_id
ws.setId(user_id)
ws.join(user_id)
console.log('Client connected');
ws.onS("hello", validateRoomId, (data: {room_id: string, message: string}) => {
console.log('Received message:', data);
wss.toRooms(data.room_id).emitS("hello", data.message)
})
ws.onS("join", validateRoomId, (data: {room_id: string}) => {
ws.join(data.room_id)
})
ws.onS("leave", validateRoomId, (data: {room_id: string}) => {
ws.leave(data.room_id)
})
},
errorHandler: (error: Error, ws: SocketConnection) => {
if(error instanceof MyError){
return ws.emitS("error", {message: error.message, code: error.code})
}
ws.emitS("exception", {message: error.message});
},
closeHandler: (ws: SocketConnection) => {
console.log('Client disconnected');
}
});
app.get('/hello', (req, res) => {
res.send('Hello World!');
wsServer.toAll().emitS("hello", "Hello World!")
});
httpServer.listen(8080, () => {
console.log('Server started on port 8080');
});
Features
- TypeScript support
- Easy to use API
- Extensible architecture
License
UNLICENSED
