neoDev
neoDev

Reputation: 3049

secure websocket using node.js and binary.js

I am streaming an mp3 file using Debian Jessie, Apache, Node.js and Binary.js, it works using http:// and ws://, but I cannot make it working using https:// and wss://... The server starts but I get this error in the browser:

WebSocket connection to 'wss://192.168.0.14:9000/' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

This is what I am trying:

index.js:

var https = require('https');
var fs = require('fs');

var hskey = fs.readFileSync('/etc/ssl/private/ssl-cert-snakeoil.key');
var hscert = fs.readFileSync('/etc/ssl/certs/ssl-cert-snakeoil.pem')

var options = {
    key: hskey,
    cert: hscert
};

httpsServer = https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("Hi from HTTPS");
}).listen(8080);


var BinaryServer = require('/home/john/node_modules/binaryjs').BinaryServer;

var server = BinaryServer({ 
    port: 9000,
    server: httpsServer
});

// callback function
server.on('connection', function(client) {
    var file = fs.createReadStream('/var/www/html/mp3/audio.mp3');
    client.send(file);
});

index.html:

<!doctype html>
<html>
    <head>
        <title>Stream audio</title>
        <meta charset="utf-8">
        <script src="https://cdn.jsdelivr.net/binaryjs/0.2.1/binary.min.js"></script>
        <script>
        var client = new BinaryClient('wss://192.168.0.14:9000');

        client.on('stream', function(stream, meta){

            var parts = [];

            stream.on('data', function(data){
                parts.push(data);
            });

            stream.on('end', function(){
                var music = document.createElement('audio');
                music.src = (window.URL || window.webkitURL).createObjectURL(new Blob(parts));
                music.controls = 'controls';
                music.preload = '';
                document.body.appendChild(music);
            });

        });
        </script>
    </head>


    <body>



    </body>
</html>

Upvotes: 1

Views: 770

Answers (1)

maksfromspb
maksfromspb

Reputation: 177

Simply terminate the SSL with Nginx proxy, and pass all request to NodeJS backend.

This is snippet for Nginx config:

     location /ws {
      proxy_set_header  X-Real-IP  $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
      proxy_redirect off;
      proxy_pass http://127.0.0.1:9000;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_buffers 8 32k;
      proxy_buffer_size 64k;
      break;
    }

Upvotes: 0

Related Questions