-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (83 loc) · 2.67 KB
/
Copy pathserver.js
File metadata and controls
97 lines (83 loc) · 2.67 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
var express = require('express');
var app = express();
var PORT = process.env.PORT || 3000;
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
app.use(express.static(__dirname + '/public'));
var clientInfo = {};
// Sends current users
function sendCurrentUsers(socket){
var info = clientInfo[socket.id];
var users = [];
if(typeof info === 'undefined'){
return;
}
Object.keys(clientInfo).forEach(function(socketId){
var userInfo = clientInfo[socketId];
if(info.room === userInfo.room){
users.push(userInfo.name);
}
});
socket.emit('message',{
name: 'System',
text: 'Current users:' + users.join(', '),
timestamp: moment.valueOf()
});
}
// Server Chat connection
io.on('connection',function(socket){
console.log('User is connected to socket.io');
socket.on('disconnect', function(){
var userData = clientInfo[socket.id];
if(typeof userData !== 'undefined'){
socket.leave(userData.room);
io.to(userData.room).emit('message',{
name:'Sysetm',
text: userData.name+' has left!',
timestamp: moment.valueOf()
});
delete clientInfo[socket.id];
}
});
socket.on('joinRoom', function(req){
clientInfo[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message',{
name:'System',
text: req.name + ' has Joined!',
timestamp: moment.valueOf()
});
});
socket.on('message', function(message){
//console.log('Message Received: '+message.text);
if(message.text === '@currentUsers'){
sendCurrentUsers(socket);
}else{
message.timestamp = moment.valueOf();
io.to(clientInfo[socket.id].room).emit('message',message);
}
// message.timestamp = moment().valueOf();
// socket.broadcast.emit('message', message); // send message to all sender except sender
// io.to(clientInfo[socket.id].room).emit('message', message); // send message to all users include sender
});
//new image get
socket.on('newImg', function(imgData) {
io.to(clientInfo[socket.id].room).emit('newImg', imgData);
});
socket.on("typing", function(data) {
socket.broadcast.to(clientInfo[socket.id].room).emit("isTyping", data);
});
/*socket.emit('message',{
text: 'This is my first tweet'
})*/
});
// Port Listen
http.listen(PORT, function(err){
if(err){
console.log(err);
}else{
console.log('Server running on '+PORT);
}
});