Skip to content

Instantly share code, notes, and snippets.

@GaetanoPiazzolla
Created May 16, 2021 21:15
Show Gist options
  • Save GaetanoPiazzolla/362956576376d3f855e16d806d7f6153 to your computer and use it in GitHub Desktop.
Save GaetanoPiazzolla/362956576376d3f855e16d806d7f6153 to your computer and use it in GitHub Desktop.
Server core implementation of direct-code
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require('cors')
const bodyParser = require('body-parser');
const port = process.env.PORT || 4001;
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
// Server var ------------
let latestCodeVersion;
let countClient = 0;
// API ------------
app.get('/latest-code', (req, res) => {
console.log('lates-code called')
if (latestCodeVersion) {
res.json({code: latestCodeVersion.code})
} else {
res.json({code: 'empty-code'})
}
})
// SOCKET -------------------
io.on("connection", (socket) => {
console.log("New client connected");
countClient++;
socket.on("disconnect", () => {
console.log("Client disconnected");
countClient--;
if (countClient === 0) {
io.emit('code-unlocked', {uuid: 'server'})
}
});
socket.on('update-code', (msg) => {
console.log('update-code event')
latestCodeVersion = msg
io.emit('update-code', msg)
});
socket.on('code-locked', (msg) => {
console.log('code-locked event')
io.emit('code-locked', msg)
})
socket.on('code-unlocked', (msg) => {
console.log('code-unlocked event')
io.emit('code-unlocked', msg)
})
});
server.listen(port, () => console.log(`Listening on port ${port}`));
@GaetanoPiazzolla
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment