This repository was archived by the owner on Nov 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconnection.js
More file actions
48 lines (41 loc) · 1.47 KB
/
connection.js
File metadata and controls
48 lines (41 loc) · 1.47 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
const config = require('./config');
const redis = require('redis');
const subscriber = redis.createClient(config.redis.port, config.redis.host);
const publisher = redis.createClient(config.redis.port, config.redis.host);
if (config.redis.password) {
subscriber.auth(config.redis.password);
publisher.auth(config.redis.password);
}
const model = require('./model');
function channel(app, name) {
return app + "/" + name;
}
exports.run = function(app, io) {
app.post('/publish/:app', function(req, res){
publisher.publish(channel(req.params.app, req.body.channel),
JSON.stringify({
name : req.body.name,
data : req.body.data
}));
res.send('published');
});
io.sockets.on('connection', function (socket) {
socket.emit('connected', {});
const app = socket.handshake.query.app;
const subscribed = [];
socket.on("subscribe", function(name){
const ch = channel(app, name);
subscribed.push(ch);
subscriber.subscribe(ch);
});
subscriber.on("message", function(channel, data){
if(subscribed.indexOf(channel) != -1) {
const obj = JSON.parse(data);
socket.emit(obj.name, channel, obj.data);
}
});
socket.on('disconnect', function() {
socket.emit('disconnected', {})
});
});
}