-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
61 lines (54 loc) · 2.23 KB
/
app.js
File metadata and controls
61 lines (54 loc) · 2.23 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
const WebSocket = require('ws')
const express = require('express')
const moment = require('moment')
const app = express()
const port = 7878; //port for https
app.get('/', (req, res) => {
res.send("Hello World");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
var webSockets = {}
const wss = new WebSocket.Server({ port: 6060 }) //run websocket server with port 6060
wss.on('connection', function (ws, req) {
var userID = req.url.substr(1) //get userid from URL ip:6060/userid
webSockets[userID] = ws //add new user to the connection list
console.log('User ' + userID + ' Connected ')
ws.on('message', message => { //if there is any message
console.log(message);
var datastring = message.toString();
if(datastring.charAt(0) == "{"){
datastring = datastring.replace(/\'/g, '"');
var data = JSON.parse(datastring)
if(data.auth == "chatapphdfgjd34534hjdfk"){
if(data.cmd == 'send'){
var boardws = webSockets[data.userid] //check if there is reciever connection
if (boardws){
var cdata = "{'cmd':'" + data.cmd + "','userid':'"+data.userid+"', 'msgtext':'"+data.msgtext+"'}";
boardws.send(cdata); //send message to reciever
ws.send(data.cmd + ":success");
}else{
console.log("No reciever user found.");
ws.send(data.cmd + ":error");
}
}else{
console.log("No send command");
ws.send(data.cmd + ":error");
}
}else{
console.log("App Authincation error");
ws.send(data.cmd + ":error");
}
}else{
console.log("Non JSON type data");
ws.send(data.cmd + ":error");
}
})
ws.on('close', function () {
var userID = req.url.substr(1)
delete webSockets[userID] //on connection close, remove reciver from connection list
console.log('User Disconnected: ' + userID)
})
ws.send('connected'); //innitial connection return message
})