Skip to content

Instantly share code, notes, and snippets.

@samsch
Created February 1, 2017 15:09
Show Gist options
  • Save samsch/88fb0bbadf2cd559fec7c5d9b8091dba to your computer and use it in GitHub Desktop.
Save samsch/88fb0bbadf2cd559fec7c5d9b8091dba to your computer and use it in GitHub Desktop.
Web socket server
const Server = require('ws').Server;
const https = require('https');
const express = require('express');
const app = express();
//Express static server stuff. This can be whatever you want, just an example of using Express.
app.use(express.static(path.join(__dirname, '../public')));
//`config` has the (absolute) paths to the files, and the desired port to run over.
const httpsServer = https.createServer({
key: fs.readFileSync(config.ssl_key),
cert: fs.readFileSync(config.ssl_cert),
}, app).listen(config.port);
const socket = new Server({
server: httpsServer,
});
socket.on('connection', function(ws) {
if(ws.upgradeReq.headers.origin !== 'ExpectedHostname') {
//You should error here.
//You should do this because web sockets don't do cross-origin checks.
}
//Yay! Successfull connection from your client!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment