forked from marvinelder/nodejs-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
47 lines (35 loc) · 1.25 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
var express = require('express');
var _ = require('underscore');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var nodes = { };
var usernames = {};
server.listen(process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.set('view options', { layout: false });
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use('/public', express.static('public'));
app.get('/', function (req, res) {
res.render('index');
});
io.sockets.on('connection', function(socket) {
socket.on('sendchat', function (data) {
io.sockets.emit('updatechat', socket.username, data);
});
socket.on('adduser', function(username) {
socket.username = username;
usernames[username] = username;
socket.emit('servernotification', { connected: true, to_self: true, username: username });
socket.broadcast.emit('servernotification', { connected: true, username: username });
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
delete usernames[socket.username];
io.sockets.emit('updateusers', usernames);
socket.broadcast.emit('servernotification', { username: socket.username });
});
});