-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (69 loc) · 2.75 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var express = require('express');
app = express()
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use('/scripts', express.static(__dirname + '/scripts/'));
app.use('/css', express.static(__dirname + '/css/'));
app.use('/gyros', express.static(__dirname + '/node_modules/gyronorm/'));
app.get('/', function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.get('/gyro', function(req, res){
res.sendFile(__dirname + "/gyro.html");
});
app.sessionToUser = {};
lastMessage={user: '', text: 'You are the first one here' }
io.on('connection', function(socket){
var userId = socket.handshake.query.username;
var room = socket.handshake.query.room
app.sessionToUser[socket.id] = userId;
socket.join(room)
console.log("New socket is " + socket.id);
socket.send(socket.id);
msg = {}
msg.text="Welcome to chat"
msg.sessionId = socket.id
io.to(socket.id).emit('login message', msg);
io.to(room).emit('login message',userId + ' connected' );
io.to(socket.id).emit('chat message', lastMessage)
// who else is in the room
io.of('/').in(room).clients((error, clients) => {
if (error) throw error;
console.log(room + " : " + clients)
for (var i =0; i < clients.length; i++ ){
console.log(" " + clients[i] + " --> " + app.sessionToUser[clients[i]]);
}
});
socket.on('disconnect', function(){
console.log(userId + ' disconnected');
io.to(room).emit('login message',userId + ' left --- ' );
});
socket.on('private message', function(msg){
lastMessage = msg;
io.to(msg.dest).emit('private message', msg );
});
socket.on('chat message', function(msg){
lastMessage = msg;
io.to(room).emit('chat message', msg );
// sending to sender-client only
// socket.emit('message', "this is a test");
// sending to all clients, include sender
// io.emit('message', "this is a test");
// sending to all clients except sender
// socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
// socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
// io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
// socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
// io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid
// socket.broadcast.to(socketid).emit('message', 'for your eyes only');
});
});
var port = process.env.PORT || 3000;
http.listen(port, function(){
console.log('listening on :' + port);
});