52 lines
1.5 KiB
JavaScript
52 lines
1.5 KiB
JavaScript
const HTTPS_PORT = 8443;
|
|
|
|
|
|
const fs = require('fs');
|
|
const https = require('https');
|
|
const static = require('node-static');
|
|
const WebSocket = require('ws');
|
|
const WebSocketServer = WebSocket.Server;
|
|
|
|
// Yes, SSL is required
|
|
const serverConfig = {
|
|
key: fs.readFileSync('key.pem'),
|
|
cert: fs.readFileSync('cert.pem'),
|
|
};
|
|
|
|
const file = new static.Server('./client');
|
|
|
|
// ----------------------------------------------------------------------------------------
|
|
|
|
// Create a server for the client html page
|
|
var handleRequest = function(request, response) {
|
|
request.addListener('end', () => {
|
|
file.serve(request, response);
|
|
}).resume();
|
|
};
|
|
|
|
var httpsServer = https.createServer(serverConfig, handleRequest);
|
|
httpsServer.listen(HTTPS_PORT, '0.0.0.0');
|
|
|
|
// ----------------------------------------------------------------------------------------
|
|
|
|
// Create a server for handling websocket calls
|
|
var wss = new WebSocketServer({server: httpsServer});
|
|
|
|
wss.on('connection', function(ws) {
|
|
ws.on('message', function(message) {
|
|
// Broadcast any received message to all clients
|
|
console.log('received: %s', message);
|
|
wss.broadcast(message);
|
|
});
|
|
});
|
|
|
|
wss.broadcast = function(data) {
|
|
this.clients.forEach(function(client) {
|
|
if(client.readyState === WebSocket.OPEN) {
|
|
client.send(data);
|
|
}
|
|
});
|
|
};
|
|
|
|
console.log('Server running. Visit https://localhost:' + HTTPS_PORT + ' in Firefox/Chrome (note the HTTPS; there is no HTTP -> HTTPS redirect!)');
|