Skip to content

Instantly share code, notes, and snippets.

@cpq
Created November 21, 2019 11:36
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 cpq/296bcb77c9875d56187432994942e89b to your computer and use it in GitHub Desktop.
Save cpq/296bcb77c9875d56187432994942e89b to your computer and use it in GitHub Desktop.
const WebSocket = require('ws'); // npm install -g ws
const server = new WebSocket.Server({port: 8000}, function() {
console.log('WS server started');
});
server.on('connection', function connection(ws, req) {
let i = 0;
ws.on('message', function incoming(message) {
console.log('received', message);
});
console.log('connected', req.connection.remoteAddress);
let t = setInterval(() => {
const msg = 'hi' + i++;
ws.send(msg);
console.log('sent', msg);
}, 1000);
ws.on('close', () => {
console.log('close');
clearInterval(t);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment