-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·63 lines (53 loc) · 1.67 KB
/
server.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
var http = require('http');
var url = require('url');
var fs = require('fs');
var io = require('./socket.io');
// TODO this is nginx task
server = http.createServer(function(req, response){
var path = url.parse(req.url).pathname;
if(path == '/'){
path = '/users.html';
}
if(path == '/users.html' || path == '/json.js'){
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(response);
response.writeHead(200, {
'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'
});
response.write(data, 'utf8');
response.end();
});
}else{
send404(response);
};
});
send404 = function(response){
response.writeHead(404);
response.write('404');
response.end();
};
// Start Server
server.listen(8080);
var socket = io.listen(server);
var logins = {};
socket.on('connection', function(client){
// Send all users to client
var sessionId = client.sessionId;
logins[sessionId] = sessionId;
client.send({ action:'init', users: logins, currentUser: sessionId});
// Send all users information about new user
client.broadcast({user: sessionId, action: 'connected' });
client.on('message', function(message) {
if('login' == message.action){
client.broadcast({
action: 'rename', sessionId: sessionId,
oldName: logins[sessionId], newName:message.login
});
logins[sessionId] = message.login;
}
});
client.on('disconnect', function() {
client.broadcast({user: sessionId, action: 'disconnected', login:logins[sessionId]});
logins[sessionId] = null;
});
});