Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where the last user to connect to a room does not receive any data. While this user can send their drawings to others, they are unable to receive any data. Below is the server-side socket code written in TypeScript:

import {User} from '../model';
export class DrawingSocket {
connectedUsers = [];
drawingConnection: any;

constructor(private socketIO: any) {
    this.socketIO.of('/sockets/drawing').on('connection', (con: any) => {
        this.drawingConnection = con;
        this.listen();
    });
    console.log("Drawing socket listening at /sockets/drawing/");
}

private listen(): void {
    this.drawingConnection.on("drawing", (data: any) => {
        console.log("[DRAWING] Room "+data.room);
        this.drawingConnection.to(data.room).emit("draw", data);
    });


    this.drawingConnection.on("clear", (data: any) => {
        console.log("[DRAWING] CLEAR for room "+data.room);
        this.drawingConnection.to(data.room).emit("clear", data);
    });

    this.drawingConnection.on("login", (user: any) => {
        this.drawingConnection.join(user.room);
        this.connectedUsers[user._id] = user;
        this.drawingConnection.to(user.room).emit("userlist", this.getSimpleUserList());
        this.drawingConnection.emit("userlist", this.getSimpleUserList());
        console.log("User " + user.name + " joined room " + user.room);
        console.log(JSON.stringify(this.socketIO.rooms));

    });

    this.drawingConnection.on("logout", (user: any) => {
        var room = this.connectedUsers[user._id].room;
        this.drawingConnection.to(room).emit("userlist", this.getSimpleUserList());
        this.drawingConnection.leave(room);
        console.log("User " + user.name + " disconnecting from room " + room + ".");
    });

    this.drawingConnection.on("disconnect", () => {
        //leave room and such
    });
}

private getSimpleUserList() {
    let list = this.connectedUsers.map((user) => user.login);
    return list;
}
}

When a client connects, I immediately send a "login" event to the server, which successfully shows the connection message on the server-side.

I would appreciate any help as this is crucial for my thesis submission next week.

Answer №1

After some investigation, the solution has been discovered - it turns out that storing the connection in the

.on('connection', (con:any)=>{this.drawingConnection=con}
event was causing issues. It was a mistake to handle it that way. Instead, passing the connection object to the listen() function and using it directly rather than relying on this.drawingConnection resolved the problem effectively.

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

Uploading Boolean Values from Switch Input (React/Typescript)

I'm facing an issue while trying to post the state value of a switch input toggle control. Whenever I use the submitRecommendation() function through a button click, I encounter a JSON parse error: Cannot deserialize instance of `boolean` out of START ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

Importing CSS properties from MUI v5 - A comprehensive guide

I'm working with several components that receive styles as props, such as: import { CSSProperties } from '@material-ui/styles/withStyles' // using mui v4 import because unsure how to import from v5 paths import { styled } from '@mui/mat ...

What is the best way to send various parameters to a component using [routerLink] or router.navigate?

My app-routing.module.ts is configured as shown below: const routes: Routes = [ { path: "branches/:branch", component: BranchesComponent }, // ... ]; In addition, in my app.component.html, I have the following code: <li> ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

WebStorm is unable to detect tsconfig paths

Currently, we are facing an issue with WebStorm identifying some of our named paths as problematic. Despite this, everything compiles correctly with webpack. Here is how our project is structured: apps app1 tsconfig.e2e.json src tests ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Adding an element to an array does not automatically reflect on the user interface

After fetching JSON data from the endpoint, I am attempting to update an array but not seeing the expected results on the frontend. export class LocationSectionComponent implements OnInit{ myControl = new FormControl(); options : string[] = [' ...

Ensuring Mongoose Schema complies with an external API

My database schema includes a mongoose User schema with the following structure: const User: Schema = new Schema({ // some other fields email: {type: String, unique: true, require: true, validate: [myValidator, 'invalid email provided'], // some ...

The types for Cypress are not being detected by my Angular tsconfig file

I'm facing an issue with my Angular tsconfig not detecting the Cypress 12.3 types. I have tried numerous solutions to resolve this problem, but nothing seems to work, except for the extreme measure of starting the project over, which I think might sol ...

Error encountered during installation of Node-gyp npm package in a Node.js project

Whenever I attempt to include node-gyp in my node project for the purpose of installing socket.io, I encounter these npm errors: I've made sure to have all the required dependencies for the installation of node-gyp: python (v2.7 preferred, v3.x.x i ...

Failed to import due to an error from the downloaded dependency

I'm encountering an import error in the @react-three module of my downloaded package. ./node_modules/@react-three/drei/node_modules/troika-three-text/dist/troika-three-text.esm.js Attempted import error: 'webgl-sdf-generator' does not cont ...

Focusing on an input element in Angular2+

How do I set focus on an input element? Not with AngularDart, but similar to the approach shown in this question: <input type="text" [(ngModel)]="title" [focus] /> //or <input type="text" [(ngModel)]="title" autofocus /> Does Angular2 provi ...

What is the best way to transform a Storybook typescript meta declaration into MDX format?

My typescript story file is working fine for a component, but new business requirements call for additional README style documentation. To meet this need, I am trying to convert the .ts story into an .mdx story. However, I am facing challenges in adding de ...

Troubleshoot TypeScript API within Angular 12 using Chrome debugger

I'm having trouble finding a solution on SO. Can anyone help me debug and check the code snippet below for hello? getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10); this.heroService.getHero(id) .sub ...

What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API. Here is my implementation for getStaticProps: export const getStaticProps: GetStatic ...

What steps do I need to follow to develop a checkbox component that mirrors the value of a TextField?

I am working with 3 components - 2 textfields and 1 checkbox Material UI component. My goal is to have the checkbox checked only when there is a value in one of the textfield components. What would be the most effective way to achieve this functionality? ...

Socketio is capable of broadcasting messages to a single recipient only

Currently, I am in the process of developing a game utilizing socketio. Within this game, the server keeps track of the number of players. Once two players have connected, the game will begin. However, I have encountered an issue where if I open two br ...

Angular 15 brings an exciting new feature: the Swiper 9 Element

I went through the swiperjs official documentation found at: swiperjs doc To display images, I created a method to configure and initialize the swiper only when necessary. Below is the HTML code snippet: <swiper-container #swiperRef init="false& ...