Issue encountered: Unable to establish successful private messaging functionality with NodeJS Socket.io

I've been having trouble for more than a week now while developing my chat app that allows users to send private messages. Unfortunately, the private message function is not working properly.

Let me provide you with the code that I'm using when a user wants to send a private message:

The code essentially checks if the intended recipient is online and retrieves their socket from the user dictionary. It then broadcasts the message to both the sender and the recipient.

As for the client-side code:

In this section of the code, it verifies whether the message should be displayed on the receiver's screen or the sender's screen.

To give you an idea about how the chat app handles new user connections, here is the relevant code:

Here, when a new user joins, we check if the username already exists in our list of users. If it does, we return false; otherwise, we add the user's nickname and socket to the system, update the list of nicknames, and emit the updated usernames to all connected sockets.

Every time I attempt to send a message, it doesn't show up on the sender's screen but appears twice on the receiver's screen. Additionally, when a third user connects, any sent messages are only displayed on the third user's screen instead of between the original two users.

Answer №1

Hey there, for server-side implementation, you can use the following code:

const socketConnections = {};

socket.on('userID', function(data) {
   socket.userID = data.userID;
   socketConnections[socket.userID];
});

socket.on('sendMessage', function(data) {
         socketConnection[data.receiverID].emit(
             'message',
             {message: data.message, senderID: socket.userID}
         );
 }); 

For the client-side, you can use the below code:

socket.emit('userID', {userID: 'anyUniqueID'});

socket.emit('sendMessage', {message: 'hi this murugan', receiverID: 'uniqueReceiverID'});

socket.on('message', function(data) {
     //Private message     
     console.log(data.message);
});

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

Is it possible to run both Express and React on the same port within the MERN Stack

Currently, I am working on a project that utilizes the MERN stack - MongoDB, Express, React, and Node. However, I have encountered an issue when attempting to post data from a form in a React component to an API endpoint defined in Node.js. Upon submission ...

How to smoothly glide to the bottom of a chat box by scrolling synchronously

I am currently in the process of developing a chat application. Each time a user sends a new message, it is added to a list of messages displayed in an unordered list (ul). I have successfully made the ul scrollable, but unfortunately, when a new message i ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

Inquiry: What is the method for setting the user agent for each request?

Is there a way to define the user agent for each request using request? Right now, I am setting it every time I make a request: request.post(url, { form: form, headers: { 'User-Agent': ua }}, function(err, resp, body) { // Do some stuff }) ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Ubuntu compatibility with chrome-driver 83

Currently using Ubuntu 18.04.1 LTS with Google Chrome version 83 and corresponding chrome-driver version 83 successfully for a while, I recently encountered an issue after updating to the latest stable versions: google-chrome-stable v83.0.4103.61 and chrom ...

Encountering a 500 internal server error or receiving an error message stating "invalid value for stripe.confirmCardPayment

I'm currently working on implementing a payment component for my React app using Stripe for the first time. Despite following a tutorial closely, I keep encountering an internal server error or receiving an "invalid value for stripe.confirmCardPayment ...

Attempting to understand the findings of the npm audit

Context Upon running the npm audit command on an old ReactJS project that we recently revisited after a year, a summary of 356 vulnerabilities was obtained (321 low, 20 moderate, 14 high, 1 critical) across 11345 scanned packages. Executing npm audit fix ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

An issue arises in the NodeJS Express authentication process when attempting to set headers after they have already been sent,

Currently, I am working on developing a basic authentication system using the POST method. app.post("/api/auth",function(req,resp) { var username = req.body.username||req.param('username'); var password = req.body.password||req.param(&a ...

Comparing GraphQL Dataloader with Mongoose Populate

When it comes to performing a join-like operation, both GraphQL and Mongoose can be utilized for achieving the desired outcome. Before posing any inquiries, consider the following example related to Task/Activities (please note that this code is purely fo ...

Comparing Procedural Database Code to Using Multiple Database Calls

Here's a question that requires a bit of thought... I'm currently in the process of designing a database and I find myself unsure about where to place the procedural logic that handles complex queries. There are two options I am considering: 1) ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Troubleshooting the issue of option tag failing to insert values into MongoDB with React and NodeJS

I am currently working on integrating the option value tags in my MERN project. However, I am facing an issue where nothing is being inserted into the database. As a beginner in learning MERN, I am struggling to identify the root cause of this problem. B ...

Providing pre-compiled native binaries through npm distribution

Can native binaries be distributed using npm, and is there any documentation available on this topic? ...

What are some strategies to keep users from navigating back using the browser after signing up?

Currently, I'm implementing an authentication system in my Node.js application using passport. Everything seems to be working smoothly except for one issue - when I click the back button in the browser, it takes me back to the signup page. This is h ...

Having trouble installing NestJS due to the error message: "ERR_INVALID_OPT_VALUE" with a clear explanation of "re readableHighWaterMark

I am trying to install NestJs/cli on my Ubuntu 16.4 system by running the command below: npm install -g @nestjs/cli However, I encountered an error while doing so: 87 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "@nestjs/cli" 8 ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Transmitting data from a server to a client in NodeJS

Help needed with emitting data from server to client. I keep getting undefined on console.log for the res variable in my client-side JavaScript code. Here is my server-side code: const express = require('express') const app = express() const se ...