Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda