This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
67 lines (50 loc) · 1.57 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
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.use(express.static('public'));
server.listen(8080,function(){
console.log("Listening at 8080");
});
io.on('connection',function(socket){
socket.on('create or join',function(room){
io.in(room).clients(function(error, clients){
if (error) {
throw error;
return;
}
if(clients.length >= 2)
{
socket.emit('errorMessage',`Could not join room. It's full!`);
return;
}
socket.join(room);
const joinMessage = {
initiator : true,
data : `You have successfully joined ${room}!`
};
if(clients.length == 0) {
socket.emit('joined room',joinMessage);
} else {
joinMessage.initiator = false;
socket.emit('joined room',joinMessage);
socket.to(room).emit('newcomer','Hi there people!');
}
console.log(`${room} room has ${clients.length} people`);
});
});
socket.on('roomMessage',function(roomMessage){
io.in(roomMessage.room).clients(function(error, clients){
if (error) {
throw error;
return;
}
if(clients.indexOf(socket.id)!==-1) {
console.log(`Client ${socket.id} sent room message : ${roomMessage.room} - ${JSON.stringify(roomMessage.data)}`);
socket.to(roomMessage.room).emit('roomMessage',roomMessage);
} else {
socket.emit('errorMessage',`You don't belong to this room kid!`);
}
});
})
});