Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!