-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
109 lines (81 loc) · 2.71 KB
/
Copy pathserver.js
File metadata and controls
109 lines (81 loc) · 2.71 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
98
99
100
101
102
103
104
105
106
107
108
109
const express = require('express')
const socket = require('socket.io')
const http = require('http') // http is present in node library
const favicon = require('serve-favicon');
// specifying heroku's env.PORT
const PORT = process.env.PORT || 4848;
const app = express()
const server = http.createServer(app)
const io = socket(server)
let usersockets = {}
app.use('/', express.static(__dirname + '/frontend'))
// `favicon.ico` is in the `public` folder
app.use(express.static('public'))
//middleware for favicon
app.use(favicon(__dirname + '/public/favicon.ico'))
// Get the `keys` for a particular `value`
function getKeyByValue(object, value) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (object[prop] === value) {
return prop;
}
}
}
}
io.on('connection', (socket) => {
console.log("Connection Established :", socket.id)
// console.log("Type of socket.id -->", typeof(socket.id)) <= string
// When the connection is made succesfully
socket.emit('connected')
socket.on('login', (data) => {
usersockets[data.user] = socket.id
// console.log(typeof (usersockets)); console.log(usersockets)
socket.broadcast.emit('alertAll', {
name: data.user,
incoming: true
})
})
socket.on("send_chat", (data) => {
if (data.recipient == null) {
// RCP is NULL, NORMAL MSSG
io.emit("recieve_chat", {
message: data.message,
username: data.username,
private: false
})
}
else {
// RCP is not NULL, PVT MSG
let rcpSocket = usersockets[data.recipient]
// when no user exists for private mssg
if (typeof (rcpSocket) == "undefined") {
console.log("No such user Found")
io.to(usersockets[data.username]).emit("recieve_chat", {
recipient: data.recipient
})
return;
}
// PRIVATE MSSG
io.to(rcpSocket).emit("recieve_chat", {
message: data.message,
username: data.username,
private: true
})
}
})
socket.on('disconnect', (reason) => {
let username = null;
console.log('user disconnected, socketID : ', socket.id);
username = getKeyByValue(usersockets, socket.id);
if (username) {
socket.broadcast.emit('alertAll', {
name: username,
incoming: false
})
}
});
})
server.listen(PORT, () => {
console.log("Server started on http://localhost:4848")
})