/
server-demo.js
79 lines (68 loc) · 2.09 KB
/
server-demo.js
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
const app = require('express')();
const server = require('http').createServer(app);
const WebSocketServer = require('ws').Server;
// require lib
// const Voicer = require('webrtc-unified/server');
// its package repository, require local file
const Voicer = require('./server.js');
// create server instance
const voicer = Voicer();
server.listen(process.env.PORT || 3000);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
['client.js', 'turn-server.js', 'client-demo.js'].forEach(file =>
app.get('/' + file, function (req, res) {
res.sendFile(__dirname + '/' + file);
})
);
let wss = (new WebSocketServer({
path: '/ws',
server,
}));
wss.on('connection', onClient);
// example connection event handler
function onClient(ws, req) {
// create client instance
// you can put off initializing client instance before getting data for this package
ws.voicer = voicer.addClient({
// function for send information(object) to client
// you must get data on client and use appropriate function in client lib
send: data => ws.send(JSON.stringify({
action: 'webrtc-unified',
data: data
})),
// user data for sending this value to client
// if don`t set client get undefined
// don`t require
// userId: some value/can be object,
// client id for sending this value to client
// if don`t set the lib sets random string
// don`t require, must be unique
// better to use userId
// clientId: string,
});
// we get some data from client
ws.on('message', mess => {
let data;
try {
data = JSON.parse(mess);
} catch (e) {
// fall
return ws.terminate();
};
// we get message for lib
if (data.action === 'webrtc-unified'){
// if you dont call voicer.addClient here, its place for do it
// if(!ws.voicer) ws.voicer = voicer.addClient({send: function})
// send message to lib
return ws.voicer.receive(data.data);
}
else console.log(data);
});
// when connection closed, use close for disconnect this user from other and destroy client instance
ws.on('close', function () {
ws.voicer.close();
ws.voicer = undefined;
});
}