-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·82 lines (68 loc) · 1.95 KB
/
server.js
File metadata and controls
executable file
·82 lines (68 loc) · 1.95 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
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8080;
var idMapping = [];
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin || "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET");
next();
});
app.get('/', function(req, res){
res.send('welcome to my chat server');
});
// usernames which are currently connected to the chat
var usernames = {};
var getSocketIdForUser = function(id) {
var socketIdToReturn = false;
idMapping.map(function(user) {
if (user.id == id) {
socketIdToReturn = user.socketId;
}
});
return socketIdToReturn;
}
io.on('connection', function (socket) {
var addedUser = false;
socket.on('register-user', function(id) {
var userFound = false;
idMapping.map(function(user) {
if (user.id === id) {
user.socketId = socket.id;
userFound = true;
}
});
if (!userFound) {
var newUser = {
id: id,
socketId: socket.id
};
idMapping.push(newUser);
}
});
socket.on('new message', function (data) {
var toSocketId = getSocketIdForUser(data.toUserId);
if (toSocketId) {
io.to(toSocketId).emit('new message', data);
io.to(socket.id).emit('new message', data);
} else {
io.to(socket.id).emit('new message', data);
}
});
socket.on('disconnect', function () {
var indexToRemove = null;
idMapping.map(function(user, index) {
if (user.socketId == socket.id) {
indexToRemove = index;
}
});
idMapping.splice(indexToRemove, 1);
});
});
app.get('/usernames', function(req, res){
res.send(usernames);
});
http.listen(port, function(){
console.log('listening on *:'+port);
});