The Socket IO server fails to broadcast a message to a designated custom room

I am currently working on developing a lobby system that allows players to invite each other using Socket io version 4. The process involves the client sending a request to create and join a room, followed by emitting messages to other clients in the same room. However, I have encountered an issue where the server successfully receives the message but fails to forward it to any clients within the room.

This is what my current code looks like:

Server

io.on('connection', (socket) => {
    const token = extractToken(socket.handshake.headers)
    const decodedToken = jwt.decode(token, { complete: true })
    const user = decodedToken.payload.user_information

    socket.leave(socket.id)
    socket.id = user.id
    socket.join(socket.id)

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

    socket.on('lobby', async (data) => {
        const { message, room } = data
        console.log(data)
        socket.to(room).emit('lobby', message)
    })

    socket.on('disconnect', () => {
        console.log(user.username + ' has disconnected')
    })
})

Client

const connect = () => {
    socket = io('localhost:8080', {
        extraHeaders: {
            authorization: 'bearer ' + token
        }
    })

    socket.on('lobby', (msg) => {
        console.log(msg)
        const item = document.createElement('li')
        item.textContent = msg
        messagesList.appendChild(item)
    })
}

messageForm.addEventListener('submit', async (e) => {
    e.preventDefault()
    if (messageInput.value) {
        await socket.emit('room', roomInput.value)
        socket.emit('lobby', { 'message': messageInput.value, 'room': roomInput.value })
        messageInput.value = ''
    }
})

While I can send global messages to all clients, I am unable to target a specific room. Despite clients joining the room upon request submission, they do not receive any messages from the room. Additionally, there are no logs indicating that clients disconnect during the process.

Various attempts to resolve this issue include utilizing the default namespace, ensuring both the server and socket emit the message, confirming the message object is defined, and verifying the room name is a string. Unfortunately, none of these solutions have proved successful thus far.

The server manages to receive the message but does not successfully broadcast it to the intended recipients within the specified room.

Answer №1

After much troubleshooting, I successfully resolved the issue at hand. It turns out replacing the auto-generated socket id with my own was causing the problem. I managed to fix it by removing the following line of code:

socket.id = user.id

Now, I just need to find a different place to store the client id.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to converting variables into a JSON Object in Javascript

I am looking for a way to insert external variables into a JSON object. An example of what I want: var username = "zvincze"; And then, using that variable to inject it into a JSON object: var json = '{"username":"VARIABLE_GOES_HERE"}' var obj ...

The elements that meet the first condition are the only ones displayed by my filter

I'm having trouble figuring out the best way to describe this scenario: I have a list of bases, each with a list of connectors (which could be one or more). I created a filter to sort my bases by their connectors, and here's what my method looks ...

Mastering the Art of Scrolling

Can someone please tell me the name of this specific scrolling technique? I am interested in using something similar for my project. Check out this example site ...

The process of combining identical data values within an array of objects

Can anyone help me with merging arrays in JavaScript? Here is an example array: [{ "team": team1, "groupname": "group1", "emp-data": [{ "id": 1, "name": "name1", }], }, { "team": team1, "groupname": "group1", " ...

handling multiple async queries in node.js using mongoose

I need to perform two separate queries on mongodb using Mongoose and ajax in an asynchronous manner. Below is the code snippet: var teams, faculties; userModel.find({}).sort('-score').exec((err, result) => { teams = result; }); ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

JavaScript regular expressions: filtering out results from the output

I'm trying to extract a specific number from a dynamically added string. The text looks like this: nisi non text600 elit, where 600 is the number I need to retrieve. Is there a way to achieve this without replacing the word text? var str = ('nis ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

Using JQuery to Identify the Clicked Div Container

Currently working on a JQuery script to determine which specific div box was clicked, but running into some issues. I understand that there are other approaches to achieve this by directly invoking functions upon clicking a div box, but I want to first ide ...

Conceal a div element using a button through JavaScript

I've been scouring various online resources for solutions, including Stack Overflow and W3Schools, but I haven't had any luck so far. Here's a simplified version of my current code: <script language="javascript"> function remove() ...

Is it advisable to incorporate both Jquery and AngularJs into progressive web applications?

Currently, I am in the process of constructing a progressive test application. So far, all the tutorials I have come across utilize native JavaScript. My inquiry is whether it is possible to leverage Jquery for streamlined code writing and implement an MVC ...

Secure API Calls with Prismic while Keeping Access Tokens Hidden

As I delve into the world of building a Vue.js web app, I find myself faced with the challenge of making calls to my Prismic repository without exposing my access token. The Rest API approach outlined here seems promising, but I'm at a loss on how to ...

Is npm installation specifically for a node server?

I'm in the process of developing a React app with webpack and utilizing npm to install different front end packages such as tabs, D3, and more. As I plan for production, I'm wondering if I specifically need to run my server as a Node server given ...

What is the best way to utilize date-fns for formatting a date retrieved from an API?

After receiving data from an API in the 'yyyy-MM-dd' format, I encountered a display issue when trying to convert it to 'dd-MM-yyyy'. How can I properly adjust the date format without disrupting the table display? onMounted(async () =& ...

Jquery ajax is failing to achieve success, but it is important not to trigger an error

My jQuery ajax request seems to be stuck in limbo - it's not throwing an error, but it also never reaches the success function. This is how my code looks: function delete() { $("input[name='delete[]']:checked").each(function() { ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

submit a unidirectional post using jquery.post

I am working with a variable named test_string which is set to the value "hello." var test_string = "hello"; I want to send this variable to a PHP page in a one-way communication. I have attempted the following: $.post('php_page.php', test_str ...

Simplify a JSON array in JavaScript by removing nested layers

Looking to flatten a JSON nested array object into a flat array The key and value pair should be dynamic based on user input array I attempted to write the code myself but I'm not very familiar with JavaScript functions like concat, push, or others. ...

issue with displaying popover component using React with Material UI

A React component I created has 6 different experiences, each triggering a popover with an array of images. The popovers are implemented using Material UI, and while they work, there are some console errors that I'm unsure how to resolve. Below is th ...

What is the best way to incorporate a condition like if the request file is not equal to req.file using

I recently made some changes to my multer code. However, when I tried adding an if statement if(!req.file) in my multer code at upload.single('name')(req, res, function (error) { within the app.post method to ensure that a file is uploaded, the e ...