generated from finos-labs/project-blueprint
-
Notifications
You must be signed in to change notification settings - Fork 61
/
index.js
73 lines (62 loc) · 1.82 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const sockio = require("socket.io");
const app = require('express')();
const winston = require('winston');
const http = require('http').createServer(app);
const io = new sockio.Server(http, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const port = process.env.TRADE_FEED_PORT || 18086;
const log = winston.createLogger({
transports: [
new winston.transports.Console()
]
});
// command names
const SUBSCRIBE = "subscribe";
const UNSUBSCRIBE = "unusbscribe";
const PUBLISH = "publish";
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
function wrapMessage( sender, topic, payloadType, payload){
return {
type: payloadType || "message",
from: sender,
topic: topic,
date: new Date().getTime(),
payload: payload
}
}
function joinMessage(user,topic){
return wrapMessage('System',topic,'message',{message: `New Joiner ${user} to topic ${topic}`});
}
function leaveMessage(user,topic){
return wrapMessage('System',topic,'message',{message: `${user} has left ${topic}`});
}
function broadcast(from, data) {
var message=wrapMessage(from,data.topic,data.type,data.payload);
log.info(`Publish ${data.topic} -> ${JSON.stringify(message)}`);
io.sockets.in([data.topic, "/*"]).emit(PUBLISH, message);
}
io.on('connection', (socket) => {
log.info(`New Connection from ${socket.id}`);
socket.on(SUBSCRIBE, (topic) => {
log.info(`Subscribe ${topic}`);
socket.join(topic);
broadcast('System', joinMessage(socket.id,topic));
});
socket.on(UNSUBSCRIBE, (topic) => {
log.info(`Unsubscribe ${topic}`);
broadcast('System', leaveMessage(socket.id,topic));
socket.leave(topic);
});
socket.on(PUBLISH, (data) => {
broadcast(socket.id, data);
});
});
http.listen(port, () => {
log.info(`Socket.IO server running at http://localhost:${port}/`);
});