-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path_server.js
More file actions
89 lines (62 loc) · 1.9 KB
/
_server.js
File metadata and controls
89 lines (62 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var Class = require('uclass');
var Options = require('uclass/options');
var WebSocketServer = require('ws').Server; //it's a good idea to try uws instead of ws
var Splitter = require('stream-split');
var NALseparator = new Buffer([0,0,0,1]);//NAL break
var _Server = new Class({
Implements : [Options],
Binds : ['new_client', 'start_feed', 'broadcast'],
options : {
width : 960,
height: 540,
},
initialize : function(server, options){
this.setOptions(options)
this.wss = new WebSocketServer({server: server});
this.wss.on('connection', this.new_client);
},
start_feed : function(){
var self = this;
this.get_feed(function(err, readStream){
self.readStream = readStream;
readStream = readStream.pipe(new Splitter(NALseparator));
readStream.on("data", self.broadcast);
});
},
get_feed : function(){
throw new Error("to be implemented");
},
broadcast : function(data){
this.wss.clients.forEach(function(socket) {
if(socket.buzy)
return;
socket.buzy = true;
socket.buzy = false;
socket.send(Buffer.concat([NALseparator, data]), { binary: true}, function ack(error) {
socket.buzy = false;
});
});
},
new_client : function(socket) {
var self = this;
console.log('New guy');
socket.send(JSON.stringify({
action : "init",
width : this.options.width,
height : this.options.height,
}));
socket.on("message", function(data){
var cmd = "" + data, action = data.split(' ')[0];
console.log("Incomming action '%s'", action);
if(action == "REQUESTSTREAM")
self.start_feed();
if(action == "STOPSTREAM")
self.readStream.pause();
});
socket.on('close', function() {
self.readStream.end();
console.log('stopping client interval');
});
},
});
module.exports = _Server;