I am making a real time multiplayer game with socket.io and node.js, I have a html file that runs a public script to connect to the server and run commands, as well as defining the library I need with
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
I have a connect and disconnect function in thew public js file that has these functions:
// send join request
function joinlobby(room) {
socket.emit("userJoined", room);
}
// emit when a player leaves
function leavelobby(room) {
socket.emit("userLeft", room);
}
and whenever I create a new socket within the function with something like
// emit when a player leaves
function leavelobby(room) {
let socket = io();
socket.emit("userLeft", room);
}
it will run correctly, however with both having a separate connection it causes issues. I was trying to have them use the same connection by having let socket = io(); placed above the functions to use the same socket, however when the program hits that line it stops running the file without throwing an error
How could I use a single connection to the server, and/or why is the program disconnecting when I define the socket outside a function?
Edit for clarity: The issue isn't wanting a single connection for every client, but rather each client has multiple connections whenever I define the socket in each respective function. I am aiming at only having 1 connection for each client but the line throws an error
I'm sorry for the ambiguity, I'm new to asking questions on here
When you create a connection to the socket server each client will have his own connection, if you want to send a single message to multiple clients you should use rooms. It is pretty easy to use:
io.on("connection", socket => {
socket.join("room1");
});
If boot clients are connected to the same room you will be able to send a message to that room.
io.to("room1").emit("Hello every body");
More info here: https://socket.io/docs/v3/rooms/