81 lines
2.1 KiB
JavaScript
81 lines
2.1 KiB
JavaScript
const PORT = process.env.PORT || 8080;
|
|
const PREFIX = process.env.PREFIX || '/ws';
|
|
const DEV = process.env.DEV || false;
|
|
console.log('Socket.io listen on: http://localhost:' + PORT + '' + PREFIX + '/socket.io');
|
|
console.log('Publisher listen on: http://localhost:' + PORT + '' + PREFIX + '/pub/$roomID');
|
|
if (DEV !== false) {
|
|
console.log('System is on DEV mode');
|
|
}
|
|
|
|
const app = require('express')();
|
|
const server = require('http').createServer(app);
|
|
var io;
|
|
|
|
if (DEV !== false) {
|
|
io = require('socket.io')(server, {path: PREFIX + '/socket.io', cors: {origin: '*',}});
|
|
} else {
|
|
io = require('socket.io')(server, {path: PREFIX + '/socket.io'});
|
|
}
|
|
|
|
const bodyParser = require('body-parser');
|
|
|
|
|
|
var jsonParser = bodyParser.json();
|
|
const queue = {};
|
|
|
|
app.get('/test', function (req, res) {
|
|
//res.send('<script src="/socket.io/socket.io.js"></script><script> const socket = io("http://localhost");</script>')
|
|
res.sendFile(__dirname + '/public/index.html')
|
|
});
|
|
|
|
app.post('/pub/:roomId', jsonParser, function (req,res) {
|
|
const room = req.params.roomId;
|
|
console.log('publish to ' + room + ' data:');
|
|
console.log(req.body);
|
|
if (typeof queue[room] !== 'undefined') {
|
|
queue[room].push(req.body);
|
|
} else {
|
|
io.to(room).emit('data',req.body);
|
|
}
|
|
console.log(queue);
|
|
res.sendStatus(200);
|
|
});
|
|
|
|
function takeFromQueue(room) {
|
|
if (typeof queue[room] == 'undefined') {
|
|
return;
|
|
}
|
|
const d = queue[room].shift();
|
|
if (typeof d === 'undefined') {
|
|
delete queue[room];
|
|
console.log("Queue delivered. Remove obj.")
|
|
return;
|
|
}
|
|
io.to(room).emit('data',d);
|
|
|
|
setTimeout(()=>{
|
|
takeFromQueue(room);
|
|
}, 500);
|
|
}
|
|
|
|
io.on('connection', function(socket) {
|
|
console.log('new user ' + socket.id);
|
|
console.log("_________________________")
|
|
if (typeof socket.handshake.query.id !== 'undefined') {
|
|
const room = socket.handshake.query.id;
|
|
socket.join(room);
|
|
console.log('user ' + socket.id + ' joined to room ' + room);
|
|
takeFromQueue(room);
|
|
}
|
|
socket.on('disconnect', () => {
|
|
const room = socket.handshake.query.id;
|
|
console.log('user ' + socket.id + ' disconnected');
|
|
queue[room]=[];
|
|
console.log('create queue: ' + room);
|
|
});
|
|
});
|
|
|
|
|
|
|
|
server.listen(PORT);
|