I'm new to using sockets, websockets, workers etc... I've never used them before.
To practice, I would like to make a simple app that is somewhat more complex than what is on the internet, which are only very basic examples.
I had thought about the game of Bingo. A server says numbers at random and the clients (not just one and on different devices), capture those numbers and fill in their respective card according to the number.
I'm lost on the subject and maybe it's easier than I thought but I really don't know.
This only works for one client, I need either one to be able to connect without the other client stopping receiving numbers.
Web socket code:
// Importing the required modules
const WebSocketServer = require('ws');
const WebSocket = require('ws');
const port = 8081
// Creating a new websocket server
const wss = new WebSocketServer.Server({ port: port })
const wsSelected = []
// Creating connection using websocket
wss.on("connection", ws => {
console.log("Nuevo cliente!");
setInterval(() => {
ws.send(Math.floor(Math.random() * 100))
}, 500)
// sending message
ws.on("message", data => {});
// handling what to do when clients disconnects from server
ws.on("close", () => {
console.log("El cliente se ha disconconetado");
});
// handling client connection error
ws.onerror = function () {
console.log("Ha ocurrido algún error")
}
});
console.log("El WebSocketServer está corriendo ene le puerto " + port);
Client code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>BINGO</title>
</head>
<body class="bg-dark text-white">
<h2>Número cantado: <span class="numero"></span></h2>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>
const ws = new WebSocket("ws://localhost:8081")
const type = "Quiero jugar al bingo!"
ws.addEventListener("open", () => {
ws.send(type)
});
ws.addEventListener('message', function (event) {
let data = JSON.parse(event.data)
console.log(data)
let numero = data
$(`.numero`).text(numero)
});
</script>
</body>
</html>