WebSocket Server
Ian Oliv / December 27, 2021
2 min read • ––– views
Setup
Install the dependencies:
yarn init -y && \
yarn add express ws cors
Simple HTTP Server with Express
// main.js
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const app = express();
app.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
app.use(helmet());
app.use(express.json());
app.use(morgan('dev'));
app.post('/login', (req, res, next) => {
res.json({ token: '123456' });
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server started on port 3000');
});
to simplify the process of setting up a simple HTTP server I use the Express framework.
WebSocket Server handling events
//ws.js
function onError(ws, err) {
console.error(`onError: ${err.message}`);
}
function onMessage(ws, data) {
console.log(`onMessage: ${data}`);
ws.send(`recebido!`);
}
function onConnection(ws, req) {
ws.on('message', (data) => onMessage(ws, data));
ws.on('error', (error) => onError(ws, error));
console.log(`onConnection`);
}
module.exports = (server) => {
const wss = new WebSocket.Server({
server
});
wss.on('connection', onConnection);
console.log(`WebSocketis running!`);
return wss;
};
the code above, I've set some default events to handle. The onError
event is called when an error occurs. The onMessage
event is called when a message is received. The onConnection
event is called when a new connection is established.
Web socket server ?
(Express Server)+(WebSocket Server) = la especilidad ✨
//main.js
// main.js
const express = require('express');
const cors = require('cors');
const appWS = require('./ws');
...
const server =app.listen(process.env.PORT || 3000, () => {
console.log('Server started on port 3000');
});
appWs(server);
And voila!
A simple HTTP server with WebSocket support.
$ node main.js
Server started on port 3000
how to Test
I use the Hoppscotch library to test my real time applications. 😉