-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
68 lines (56 loc) · 2.18 KB
/
app.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
var app = require('express').createServer();
var io = require('socket.io').listen(app);
var port = process.env.PORT || 4004;
app.listen(port, function () {
var addr = app.address();
console.log('app listening on http://' + addr.address + ':' + addr.port);
});
app.get( '/', function( req, res ){
res.sendfile( __dirname + '/index.html' );
});
app.get( '/*' , function( req, res, next ) {
var file = req.params[0];
console.log('\t :: Express :: file requested : ' + file);
res.sendfile( __dirname + '/' + file );
});
io.set('log level', 1);
// users which are currently connected to the chat
var users = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username, id){
var d = new Date();
var timestamp = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
socket.username = username;
socket.id = id;
users[socket.id] = username;
// echo to room 1 that a person has connected to their room
io.sockets.emit('updatechat', 'SERVER', username + ' has connected', timestamp);
console.log("Added user " + socket.username + " with id " + socket.id);
});
socket.on('sendchat', function (data) {
var d = new Date();
var timestamp = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
io.sockets.emit('updatechat', socket.username, data, timestamp);
});
// Start listening for mouse move events
socket.on('mousemove', function (data) {
//send to everyone but the originating client
io.sockets.emit('moving', data);
});
socket.on('clear', function () {
//send to everyone but the originating client
io.sockets.emit('clearcanvas');
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
var d = new Date();
var timestamp = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
// remove the username from global usernames list
delete users[socket.id];
// update list of users client side
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected', timestamp);
io.sockets.emit('updateusers', users);
console.log("User " + socket.username + " left");
});
});