-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (61 loc) · 2.21 KB
/
index.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
'use strict'
const express = require('express');
const app = express();
const server = require('http').createServer(app).listen(8080, function () {
console.log("Open http://localhost:8080 in broswer");
});
const io = require('socket.io').listen(server);
const path = require('path');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
})
app.use('/js', express.static(path.join(__dirname, '/js')));
app.use('/css', express.static(path.join(__dirname, '/css')));
io.sockets.on('connection', function (socket) {
function log() {
const array = ['Message from server : '];
array.push.apply(array, arguments);
socket.emit('log', array);
}
socket.on('message', function (message, room) {
log('Client said : ', message);
// socket.broadcast.to(room).emit('message', message);
socket.to(room).emit('message', message);
});
socket.on('streaming', function (room) {
socket.to(room).emit('play');
});
socket.on('create or join', function (room) {
log('Create or Join room' + room);
const clientsInRoom = io.sockets.adapter.rooms[room];
const numClients = numClientsInRoom(clientsInRoom, room);
if (numClients === 0) {
log('Client ID ' + socket.id + 'created room' + room);
socket.join(room);
socket.emit('created', room, socket.id);
} else if (numClients === 1) {
log('Client ID ' + socket.id + 'joined room' + room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.sockets.in(room).emit('ready');
} else {
socket.emit('full', room);
}
});
socket.on('disconnect', function (event) {
console.log(`Peer or Server disconnected. Reason : ${event}`);
socket.broadcast.emit('bye');
});
socket.on('bye', function (room) {
console.log(`Peer said bye on room ${room}`);
});
});
function numClientsInRoom(clientsInRoom, room) {
if (clientsInRoom === undefined) {
console.log('Create room : ', room);
return 0;
} else {
console.log('Join room : ', room);
return clientsInRoom.length;
}
}