-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
103 lines (79 loc) · 2.2 KB
/
app.js
File metadata and controls
103 lines (79 loc) · 2.2 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const config = require('./config');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/status', (request, response) => response.json({ clients: clients.length }));
const PORT = 3000;
const conn = mysql.createConnection(config.mysql);
let clients = [];
let livestreamEvents = [];
var mid = 102;
var pid = 100;
app.listen(PORT, process.env.PORT, () => {
console.log(`Livestream service starting`);
});
function eventsHandler(request, response) {
console.log("receive")
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
};
response.writeHead(200, headers);
const data = {
key: 'connect'
}
response.write(JSON.stringify(data));
const clientId = Date.now();
const newClient = {
id: clientId,
response,
};
clients.push(newClient);
request.on('close', () => {
console.log(clientId);
});
}
app.get('/receive', eventsHandler);
app.get('/', (req,res)=>{
res.send("hi?")
})
async function addLivestreamEvent(request, response) {
console.log("send")
if (request.body.menu == undefined) {
// Mining Event
console.log("mining");
conn.query(`insert into mining values(0)`,(err,rows,field)=>{
if(err) throw err;
})
request.body.mid = mid;
request.body.type = 'mining';
mid += 1;
} else {
// PAY Event
console.log("paying");
conn.query(`insert into pay values(0)`,(err,rows,field)=>{
if(err) throw err;
})
request.body.bid = pid;
request.body.type = 'block';
}
const livestreamEvent = request.body;
livestreamEvents.push(livestreamEvent);
console.log("body", request.body);
response.json(livestreamEvent);
sendEventsToAll(livestreamEvent);
}
app.post('/send', addLivestreamEvent);
function sendEventsToAll(livestreamEvent) {
clients.forEach((client) => {
const jsonEvent = JSON.stringify(livestreamEvent);
client.response.write('data: $(jsonEvent}/n/n');
})
}