Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
How do I use a single connection with socket.io

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda