-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
50 lines (42 loc) · 1.38 KB
/
index.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
const WebSocket = require('ws');
const Url = require('url');
const _port = 9090;
const wss = new WebSocket.Server({ port: _port }, () => {
console.log(`started on port ${_port}`);
});
process.on('SIGINT', function() {
console.log('Dying');
wss.close();
process.exit();
});
wss.on('connection', function connection(socket, req) {
console.log(`USER CONNECTED: ${req.connection.remoteAddress}`);
var params = Url.parse(req.url, true).query;
socket.topicName = params.topicName;
socket.on('message', (messagestring) => {
console.log(`Received: ${messagestring} `);
try {
let message = JSON.parse(messagestring);
if (message.topic) {
wss.clients.forEach(function each(client) {
if(client.topicName){
if (client.topicName == message.topic){
client.send(JSON.stringify(message));
}
}
else {
console.log(`No topic in ${JSON.stringify(message)}`)
}
});
}
} catch (error) {
console.log(error)
}
});
socket.on('disconnect', function () {
console.log('USER DISCONNECTED');
});
socket.on('close', function () {
console.log('USER CLOSED');
});
});