-
Notifications
You must be signed in to change notification settings - Fork 409
/
server.js
43 lines (43 loc) · 1.59 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
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
users = [];
//specify the html we will use
app.use('/', express.static(__dirname + '/www'));
//bind the server to the 80 port
//server.listen(3000);//for local test
server.listen(process.env.PORT || 3000);//publish to heroku
//server.listen(process.env.OPENSHIFT_NODEJS_PORT || 3000);//publish to openshift
//console.log('server started on port'+process.env.PORT || 3000);
//handle the socket
io.sockets.on('connection', function(socket) {
//new user login
socket.on('login', function(nickname) {
if (users.indexOf(nickname) > -1) {
socket.emit('nickExisted');
} else {
//socket.userIndex = users.length;
socket.nickname = nickname;
users.push(nickname);
socket.emit('loginSuccess');
io.sockets.emit('system', nickname, users.length, 'login');
};
});
//user leaves
socket.on('disconnect', function() {
if (socket.nickname != null) {
//users.splice(socket.userIndex, 1);
users.splice(users.indexOf(socket.nickname), 1);
socket.broadcast.emit('system', socket.nickname, users.length, 'logout');
}
});
//new message get
socket.on('postMsg', function(msg, color) {
socket.broadcast.emit('newMsg', socket.nickname, msg, color);
});
//new image get
socket.on('img', function(imgData, color) {
socket.broadcast.emit('newImg', socket.nickname, imgData, color);
});
});