WebRTC-Example/server/server.js

59 lines
1.9 KiB
JavaScript

const HTTPS_PORT = 8443;
const devcert = require('devcert');
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
// ----------------------------------------------------------------------------------------
// Create a server for the client html page
const handleRequest = function(request, response) {
// Render the single client html file for any request the HTTP server receives
console.log('request received: ' + request.url);
if (request.url === '/') {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(fs.readFileSync('client/index.html'));
} else if (request.url === '/webrtc.js') {
response.writeHead(200, { 'Content-Type': 'application/javascript' });
response.end(fs.readFileSync('client/webrtc.js'));
}
};
devcert.certificateFor('webrtc.example').then(function(ssl) {
const httpsServer = https.createServer(ssl, handleRequest);
httpsServer.listen(HTTPS_PORT, '0.0.0.0');
// ----------------------------------------------------------------------------------------
// Create a server for handling websocket calls
const 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://webrtc.example:' +
HTTPS_PORT +
' in Firefox/Chrome.\n\n\
Some important notes:\n\
* Note the HTTPS; there is no HTTP -> HTTPS redirect.\n\
* Some browsers or OSs may not allow the webcam to be used by multiple pages at once. You may need to use two different browsers or machines.\n'
);
});