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

Creating a unique user interface for VSCode extension

Recently, I've delved into the world of developing extensions for Visual Studio. Unfortunately, my expertise in TypeScript and Visual Studio Code is quite limited. My goal is to create an extension that mirrors the functionality of activate-power-mod ...

Guide to customizing the layout preview specifically for certain components in Storybook, without affecting all components

Currently working on my storybook project and facing an issue. I'm aiming to have the layout centered in the preview section. I attempted export const parameters = { layout: 'centered', }; in the .storybook/preview.js file However, this c ...

Tips for updating an array in TypeScript with React:

Encountering an issue while updating my state on form submission in TypeScript. I am a newcomer to TS and struggling to resolve the error. enum ServiceTypeEnum { Replace = 'replace product', Fix = 'fix product', } interface IProduc ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

Is there a way to create a tuple property that can be called like a

I have a specific function in my code: function test(cb: Function | number) { let item = { height: 0} if(typeof cb === 'number') { item.height = cb; } if(typeof cb === 'object') { item.height = cb(); } } This function ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Allow for an optional second parameter in Typescript type definition

Here are two very similar types that I have: import { VariantProps } from "@stitches/core"; export type VariantOption< Component extends { [key: symbol | string]: any }, VariantName extends keyof VariantProps<Component> > = Extra ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

The type of 'username' cannot be determined without specifying the reference to '@angular/forms/forms' in the node modules

I'm encountering an issue with my application: forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not po ...

"Refining MongoDB queries with a filter after performing a populate

I want to retrieve all records with populated attributes in a query. Here is the TypeScript code: router.get("/slice", async (req, res) => { if (req.query.first && req.query.rowcount) { const first: number = parseInt(req.qu ...

NG8003 error: ExportAs 'ngForm' directive not found in the system

I encountered an issue with my first Angular 11 project: No directive found with exportAs 'ngForm'. Despite importing FormsModule and ReactiveFormsModule in app.module.ts, the error persists. Here is the code snippet: This is from product.compon ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

Ensuring Input Validity in Angular4 and Symfony3

Currently, I am utilizing angular 4 and symfony3. In my application, there is a textarea that is required. However, when I only press enter (code 13) in this textarea without entering any other character, the form gets submitted. How can I prevent this spe ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...