Skip to content

Instantly share code, notes, and snippets.

@RolphH
Created February 16, 2021 16:21
Show Gist options
  • Save RolphH/d98dab9acb2f25f18d21a4acc0c36489 to your computer and use it in GitHub Desktop.
Save RolphH/d98dab9acb2f25f18d21a4acc0c36489 to your computer and use it in GitHub Desktop.
Small node.js application with websocket
#!/usr/bin/env nodejs
const http = require('http');
const WebSocket = require('ws');
const express = require('express');
const app = express();
const PORT = 8080;
const WS_PORT = 8081;
app.use(express.json());
// Create a WebSocket Server so clients can connect to it
const wss = new WebSocket.Server({ port: WS_PORT })
wss.on('connection', function connection(ws) {
});
// Now we create a simple HTTP server which receives a message
// and forwards the message to the connected WebSocket clients
app.get('/', (req, res) => {
res.send('Hello');
});
app.post('/', (req, res) => {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(req.body));
}
});
res.sendStatus(200);
});
app.listen(PORT, () => {
console.log('The server is running at port 8080!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment