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

132
Views
Emit to a specific room using SocketIo

I'm trying to allow users on client-side pages to chat with other users on the same page (a room), but not with users on different pages. Right now my socket is emitting across all pages. I'd like to confine the emissions to one room for each page.

App.js server side code

const io = require('socket.io')(server, { cors: { origin: "*"}});

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
  });

Client side tag

    <script src="/javascripts/socketIo.js"></script>

SocketIo.js

const socket = io();
const messages = document.getElementById('messages');
const form = document.getElementById('form');
const input = document.getElementById('input');

socket.on('connection', (socket) => {
    socket.join(room);
});

form.addEventListener('submit', function (e) {
    e.preventDefault();
    if (input.value) {
        const alias = socket.id.slice(-5);
        socket.emit('chat message', alias + ": " + input.value);
        input.value = '';
    }
});

socket.on('chat message', function (msg) {
    const item = document.createElement('ul');
    item.textContent = msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
});

The current code sends messages to all users (no rooms). If I update the code below to include prefix "socket.to" like the docs instruct, messages stop sending altogether.

from

socket.emit('chat message', alias + ": " + input.value)

to

socket.to(room).emit('chat message', alias + ": " + input.value)

How do I get socket to send the messages to page-specific rooms?

about 4 years ago · Santiago Gelvez
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!