Skip to content

Instantly share code, notes, and snippets.

@ridomin
Created May 31, 2020 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ridomin/9fd56e71715c392cc83ef9d15e344d75 to your computer and use it in GitHub Desktop.
Save ridomin/9fd56e71715c392cc83ef9d15e344d75 to your computer and use it in GitHub Desktop.
WebSocketsDemo
var wsUri = "ws://127.0.0.1:8999";
ws = new WebSocket(wsUri);
ws.onopen = (e) => console.log(e)
ws.onmessage = (e) => console.log(e)
import express from 'express';
import http from 'http';
import WebSocket from 'ws';
const app = express();
app.use(express.static('ui'));
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('received: %s', message);
ws.send(`Hello, you sent -> ${message}`);
});
ws.send('Hi there, I am a WebSocket server');
});
server.listen(process.env.PORT || 8999, () => {
console.log(`Server started on port ${server.address().port} :)`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment