I have a WebSocket hosting on repl.it
But when the repl sleeps, the WebSocket does as well.
My friends told me to have a pinger to ping the site. It doesn't work.
They told me to fetch the server.
That doesn't work either, because when the repl sleeps, CORS is disabled although my code enables CORS.
What do I do?
SERVER CODE (NODEJS):
const express = require('express');
const fs = require("fs");
const path = require('path');
const cors = require('cors')
const app = express();
const server = require('http').createServer(app);
const WebSocket = require("ws")
const wss = new WebSocket.Server({ server })
app.use(cors())
app.use(express.json());
app.use(express.static('release'));
app.use('/assets', express.static('assets'));
app.use((_, res) => {
res.status(404).sendFile(path.join(__dirname, '/error/404.html'));
});
wss.on('connection', ws => {
fs.readFile("highscore.txt", 'utf-8', (err, val) => {
if (err) throw err;
wss.clients.forEach(client => {
if (client === ws) {
client.send(`I ${val}`)
}
})
console.log(val);
});
console.log('socket connected!');
ws.on("message", msg => {
let msgs = msg.split(" ");
let pre = msgs[0]
if (pre == "R") {
fs.readFile("highscore.txt", 'utf-8', (err, val) => {
let score = msgs[1]
if (err) throw err;
if (val < score) {
console.log(`There is a new score! That is:${score}`);
fs.writeFile('highscore.txt', score, (err) => { })
wss.clients.forEach(client => {
client.send(`U ${score}`)
})
};
});
}
});
});
server.listen(2195, () => {
console.log(`server running`);
});
CLIENT CODE
import { loadProgress } from './main'
let socket;
function init(details) {
fetch("https://space-chaos--coder2195text.repl.co")
.then(response => {
return response.text();
})
.then(final => {
console.log(final)
loadProgress.update("ws", 100)
socket = new WebSocket("wss://space-chaos--coder2195text.repl.co/")
socket.onmessage = (msg) => {
let msgs = msg.data.split(" ")
if (msgs[0] === "U") {
details.update(msgs[1])
} else if (msgs[0] === "I") {
details.init(msgs[1])
}
}
})
}
function requestPush(score) {
let t = setInterval(() => {
if (socket) {
if (socket.readyState === 1) {
socket.send(`R ${score}`);
clearInterval(t)
}
}
}, 100)
}
export { requestPush, init };
```