Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Created May 22, 2018 00:30
Show Gist options
  • Select an option

  • Save acdcjunior/45ee38aaf11baed34b33d2aae29c827d to your computer and use it in GitHub Desktop.

Select an option

Save acdcjunior/45ee38aaf11baed34b33d2aae29c827d to your computer and use it in GitHub Desktop.
websocket express server client example
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3000/');
ws.on('open', function open() {
ws.send('sent by client');
});
ws.on('message', function incoming(data) {
console.log('received @client', data);
});
npm i express express-ws ws
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
app.use(function (req, res, next) {
console.log('middleware');
req.testing = 'testing';
return next();
});
app.get('/', function(req, res, next){
console.log('get route', req.testing);
res.end();
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log('received @server', msg);
ws.send('sent by server');
});
console.log('socket', req.testing);
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment