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