stream-server.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var STREAM_PORT = 8082,
  2. STREAM_SECRET = 's3cret', // CHANGE THIS!
  3. WEBSOCKET_PORT = 8084,
  4. STREAM_MAGIC_BYTES = 'jsmp'; // Must be 4 bytes
  5. var clients = {};
  6. var width = 320,
  7. height = 240;
  8. // Websocket Server
  9. var socketServer = new (require('ws').Server)({port: WEBSOCKET_PORT});
  10. var _uniqueClientId = 1;
  11. var socketError = function() { /* ignore */ };
  12. socketServer.on('connection', function(socket) {
  13. // Send magic bytes and video size to the newly connected socket
  14. // struct { char magic[4]; unsigned short width, height;}
  15. var streamHeader = new Buffer(8);
  16. streamHeader.write(STREAM_MAGIC_BYTES);
  17. streamHeader.writeUInt16BE(width, 4);
  18. streamHeader.writeUInt16BE(height, 6);
  19. socket.send(streamHeader, {binary:true}, socketError);
  20. // Remember client in 'clients' object
  21. var clientId = _uniqueClientId++;
  22. clients[clientId] = socket;
  23. console.log(
  24. 'WebSocket Connect: client #' + clientId +
  25. ' ('+Object.keys(clients).length+' total)'
  26. );
  27. // Delete on close
  28. socket.on('close', function(code, message){
  29. delete clients[clientId];
  30. console.log(
  31. 'WebSocket Disconnect: client #' + clientId +
  32. ' ('+Object.keys(clients).length+' total)'
  33. );
  34. });
  35. });
  36. // HTTP Server to accept incomming MPEG Stream
  37. var streamServer = require('http').createServer( function(request, response) {
  38. var params = request.url.substr(1).split('/');
  39. width = (params[1] || 320)|0;
  40. height = (params[2] || 240)|0;
  41. if( params[0] == STREAM_SECRET ) {
  42. console.log(
  43. 'Stream Connected: ' + request.socket.remoteAddress +
  44. ':' + request.socket.remotePort + ' size: ' + width + 'x' + height
  45. );
  46. request.on('data', function(data){
  47. for( c in clients ) {
  48. clients[c].send(data, {binary:true}, socketError);
  49. }
  50. });
  51. }
  52. else {
  53. console.log(
  54. 'Failed Stream Connection: '+ request.socket.remoteAddress +
  55. request.socket.remotePort + ' - wrong secret.'
  56. );
  57. response.end();
  58. }
  59. }).listen(STREAM_PORT);
  60. console.log('Listening for MPEG Stream on http://127.0.0.1:'+STREAM_PORT+'/<secret>/<width>/<height>');
  61. console.log('Awaiting WebSocket connections on ws://127.0.0.1:'+WEBSOCKET_PORT+'/');