socket.io - verify if a user is located in a particular chatroom

I am trying to determine if a client is subscribed to a specific room. I have an array where sockets are saved with usernames as indexes. I have an if statement, but it doesn't seem to be working:

if(io.sockets.manager.rooms['/' + data.to].indexOf(users[partner].socket.id) >= 0) {

If anyone has a solution that works, it would be greatly appreciated.

UPDATE: Here is the code:

/* MYSQL SETUP HERE FOR CONNECTION */
var count = 0;
var messages = 0;
var users = {};

var io = require('socket.io')(3000);

io.sockets.on('connection', function(client) {
    count++;
    client.emit('send login');
    client.on('login user',function (data) {
        if(data.name in users) {

        } else {
            client.u_name = data.name;
            client.u_id = data.id;
            users[client.u_id] = {'name':client.username,'socket':client};
            io.sockets.emit('online users', { 'count': count });
        }
    });
  client.on('disconnect', function(){
    count--;
    delete users[client.username];
    io.sockets.emit('online users', { 'count': count });
  });
  client.on('join',function(room){
    client.join(room);
  });
  client.on('leave',function(room){
    client.leave(room);
  });
  client.on('new message',function (data) {
    if(client.u_id in users) {
          connection.query('INSERT INTO chats_msg(u_from,chat_id,msg) VALUES(?,?,?)', [client.u_id,data.to,data.msg], function(err, rows, fields) {
              if (err) console.log(colors.red('ERROR at Query'));
              query('UPDATE chats SET last_msg=?,last_time=CURRENT_TIMESTAMP,last_from=? WHERE id=?',[data.msg,client.u_id,data.to]);
            });
        io.sockets.in(data.to).emit('message',{'msg':data.msg,'from':client.u_name});
        connection.query('SELECT * FROM chats WHERE id=? LIMIT 1', data.to, function(err, rows, fields) {
              if (err) console.log(colors.red('ERROR at QUERY'));
              if(rows[0].u_1 == client.u_id) {
                var partner = rows[0].u_2;
              } else {
                var partner = rows[0].u_1;
              }
              if(io.sockets.manager.rooms['/' + data.to].indexOf(users[partner].socket.id) >= 0) {
                  users[partner].socket.emit('error msg','New message');
                } else {
                    users[partner].socket.emit('error msg','YEAHH');
                }
            });
        messages++;
      } else {
        client.emit('error msg','Client or you are not online');
      }
  });
});

Answer №1

One useful method using the socket id is:

io.sockets.adapter.sids[socket.id][roomname]

This will return true if the socket is in the specified room, and undefined if it is not.

(tested with version 1.4.5)

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

Ensuring DIV Stays Within Window Limits using Javascript

Hi there! I'm working on a 'box' div that moves when you click arrows. How can I make sure the box stays within the window and doesn't go past the borders? Here's the fiddle: var elementStyle = document.getElementById("divId").st ...

Implementing the Context API with React Router: using version '^5.2.0' of react-router-dom and version '17.0.2' of React

I am currently struggling to retrieve the user value from my Header component using the Context API, but unfortunately it is returning as undefined. Below is my code snippet. import React, { createContext, useEffect, useState } from "react"; exp ...

Switching the parameter to navigate to the appropriate page

Hi there, I'm looking to implement a quick change using the onchange parameter. Can someone assist me in using the onchange parameter to navigate to a new page? So, if someone selects for instance Basic info, they will be directed to a new page custo ...

Sending Javascript Variable through Form

I'm a newcomer to JavaScript and struggling to solve a particular issue in my script. I need help passing the variable "outVal" to a PHP script when the submit form is clicked. The value of "outVal" should come from the "output" value in the script. I ...

Utilize a dual-color gradient effect on separate words within the <li> element

I am attempting to display the fizz buzz function in an unordered list, with each word being a different color ('fizz'-- green, 'buzz'--blue) as shown here: https://i.sstatic.net/Yvdal.jpg I have successfully displayed "fizz" and "buz ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

What are your top choices for customizable dropdowns/menus with enhanced features?

I came across a cool feature on the YUI website, check it out here: http://developer.yahoo.com/yui/examples/button/btn_example07.html Does anyone have recommendations for a library/plugin to enhance native select element dropdowns in response to a client& ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Generate the maximum capacity 3D box that can be inscribed within a set of points

I am working with a 3D mesh composed of a collection of 3D points (vertices) and a series of faces (connections between points). Q1 Is there a method to determine the largest inscribed box (volume) that can fit inside the mesh? [OP] Greetings everyone, ...

Issue with updating onclick attribute of popover in Bootstrap 4

My goal is to design a popover in bootstrap 4 with a nested button inside it. However, when I update the data-content attribute of the popover with the button element, the element gets updated but the onclick attribute goes missing. I have experimented wi ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...

Is it possible to use $.post and $.get to update the title without changing the logging functionality?

Here is a portion of my code where I am posting to a link. The issue I am facing is that it allows me to change the title, but for some reason, it does not call the function info() with the argument provided. Additionally, it does not log anything in the c ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Tips on managing the onKeyUp event in a ReactJS form

Here is a simple JavaScript function called numericOdds implemented in home.js file: function numericOdds(e) { var valid = /^[1-9]{1}[0-9]{0,1}$/ var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/ var lastValid = ''; var n; console.log(&apo ...

The scaling of the slick carousel image is not working as expected

Having an issue with the Slick carousel where images are not resizing based on browser size (original size is 300x228px). Just to clarify: When I shrink the browser window, the number of slides decreases but the images remain the same size. I've bee ...

Vue.js encountering an issue of receiving null for the JSON data upon the initial loading phase

Currently, I am expanding my knowledge on vue.js and experimenting with calling a json file to parse the data. Although everything seems to be functioning as intended, whenever I refresh the page, there is a momentary blank screen before the data loads. In ...

Display nested array objects of varying levels within VUE

How do I display nested elements on the UI when dynamically generated based on a parent element's selected option (e.g. List)? For example, in the code below, when creating a field and selecting the List option, another nested should appear, and so o ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...