Connect twice with the Socket.IO client

Every time my socket io client connects to the server, it seems to happen twice. You can see what I mean by looking at this screenshot of the double connection.

This project is built in Angular 2, so I'm coding in TypeScript:

class Server {
    private app = express();
    private httpServer = http.createServer(this.app);
    private io = sio.listen(this.httpServer);
    private users = Array<User>();
    constructor() {
        // routing to index.html
        this.app.get('/',(req, res) => {
            res.sendFile(__dirname + '/index.html');
        });
        // adding dependencies
        this.app.use(express.static(__dirname + '/');
        // connection & disconnection
        this.io.on('connection', (socket: SocketIO.Socket) => {
            var date = new Date();
            console.log(date+' : a user connected '+socket.id);
            
            socket.on('broadcast users srv',(user) => {
                var b = new Branch();
                var n = new NVNode(b);n.image_path = user._node._image_path;
                var u = new User(user._mail,user._id,n);
                u.socket = socket.id;
                this.users.push(u);
                socket.broadcast.emit('broadcast users clt',u)
            });
          });
      }
}

I tried to adjust my code like this:

class Server {
    private app = express();
    private httpServer = http.createServer(this.app);
    private io = sio.listen(this.httpServer);
    private users = Array<User>();
    private s : SocketIO.Socket
    constructor() {
        // routing to index.html
        this.app.get('/',(req, res) => {
            res.sendFile(__dirname + '/index.html');
        });
        // adding dependencies
        this.app.use(express.static(__dirname + '/');
        // connection & disconnection
        this.io.on('connection', (sock: SocketIO.Socket) => {
            var date = new Date();
            console.log(date+' : a user connected '+sock.id);
            this.s = sock;
            
        });
        
        this.s.on('broadcast users srv',(user) => {
            var b = new Branch();
            var n = new NVNode(b);n.image_path = user._node._image_path;
            var u = new User(user._mail,user._id,n);
            u.socket = this.s.id;
            this.users.push(u);
            this.s.broadcast.emit('broadcast users clt',u)
        });
      }
}

However, when I attempted this modification, an error occurred: server error message

The error indicates that the value is not initialized and appears as "undefined."

I am quite unsure about how to proceed with this issue. Any suggestions or ideas would be greatly appreciated!

Answer №1

this.s remains uninitialized until this.io triggers a "connection" event. If you only initialize it in that specific location, then you can only attach other events to this.s once a connection is established.

Transitioning from

    this.io.on('connection', (sock: SocketIO.Socket) => {
        var date = new Date();
        console.log(date+' : a user connected '+sock.id);
        this.s = sock;

    });

    this.s.on('broadcast users srv',(user) => {
        var b = new Branch();
        var n = new NVNode(b);n.image_path = user._node._image_path;
        var u = new User(user._mail,user._id,n);
        u.socket = this.s.id;
        this.users.push(u);
        this.s.broadcast.emit('broadcast users clt',u)
    });

to

    this.io.on('connection', (sock: SocketIO.Socket) => {
        var date = new Date();
        console.log(date+' : a user connected '+sock.id);
        this.s = sock;

        this.s.on('broadcast users srv',(user) => {
            var b = new Branch();
            var n = new NVNode(b);n.image_path = user._node._image_path;
            var u = new User(user._mail,user._id,n);
            u.socket = this.s.id;
            this.users.push(u);
            this.s.broadcast.emit('broadcast users clt',u)
        });
    });

could potentially solve the issue at hand.

Answer №2

Prior to initialization, avoid using the variable s. To prevent it from being undefined, move the call to this.s.on inside the callback for this.io.on.

class Server {
  private app = express();
  private httpServer = http.createServer(this.app);
  private io = sio.listen(this.httpServer);
  private users = Array<User>();
  private s: SocketIO.Socket;
  
  constructor() {
    // Routing to index.html
    this.app.get('/', (req, res) => {
        res.sendFile(__dirname + '/index.html');
    });

    // Adding dependencies
    this.app.use(express.static(__dirname + '/'));
    
    // Connection and disconnection handling
    this.io.on('connection', (sock: SocketIO.Socket) => {
        var date = new Date();
        console.log(date + ' : a user connected ' + sock.id);
        this.s = sock;

        this.s.on('broadcast users srv', (user) => {
          var b = new Branch();
          var n = new NVNode(b);
          n.image_path = user._node._image_path;
          var u = new User(user._mail, user._id, n);
          u.socket = this.s.id;
          this.users.push(u);
          this.s.broadcast.emit('broadcast users clt', u)
        });
    });
  }
}

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

Create a function to set initial values for variables in a TypeScript class

I have the following code snippet in my constructor to initialize the variables. public Elements: Observable<dcElementDataStoreItem>; private elementSubjectData: BehaviorSubject<dcElementDataStoreItem>; constructor() { this.elementSubjectDa ...

Angular 17 doesn't seem to be correctly implementing *ngIf to hide the div

After spending hours trying to display a div based on certain conditions using *ngIf in Angular, I am still unable to make it work. The following code is not showing the expected result: <div *ngIf="item.billingItem=='Staff'">This ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...

Angular applications can redirect to their own internal pages when linking to an external URL

I've recently started using Angular and have encountered a minor issue. My routing setup is working as expected in the navbar, but I have a link that points to an external URL. When I click on it, instead of redirecting me to the external site, it ta ...

Testing unsubscribe on ngOnDestroy with Angular 5 and Jasmine by mocking activeRoute.firstChild

When working on my Angular component, I set up two observables using the code below: this.navigationEnd = this.router.events.subscribe((event: any) => { // do some stuff }); if (this.activeRoute.firstChild) { this.activeRouteChild = this.activeRou ...

Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error: "error": "Cannot read property 'co ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

NgZone is no longer functioning properly

Seemingly out of the blue, my NgZone functionality has ceased to work. I'm currently in the process of developing an application using Ionic, Angular, and Firebase. An error is being thrown: Unhandled Promise rejection: Missing Command Error ; Zon ...

When I define a type in TypeScript, it displays "any" instead

Imagine a scenario where we have a basic abstract class that represents a piece in a board game such as chess or checkers. export abstract class Piece<Tags, Move, Position = Vector2> { public constructor(public position: Position, public tags = nul ...

Modifying the name of a key in ng-multiselect-dropdown

this is the example data I am working with id: 5 isAchievementEnabled: false isTargetFormEnabled: true name: "NFSM - Pulse" odiyaName: "Pulse or" when using ng-multiselect-dropdown, it currently displays the "name" key. However, I want ...

Creating a TypeScript shell command that can be installed globally and used portably

I am looking to create a command-line tool using TypeScript that can be accessed in the system's $PATH once installed. Here are my criteria: I should be able to run and test it from the project directory (e.g., yarn command, npm run command) It must ...

What is the solution to fixing a 400 bad request error in Angular Routing?

Encountering an issue on a particular route where a 400 error is displayed in the screenshot every now and then. It seems to work fine for a few minutes after deleting cookies, but the error resurfaces after accessing it multiple times. Other routes are fu ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

The server is taking too long to respond, resulting in a 504 Timeout error

I currently have an Angular frontend paired with a .NET CORE backend. The issue I am experiencing is related to a specific request that is resource-intensive and takes a significant amount of time to complete. Whenever I check the browser console, I receiv ...

Automatically expand all PrimeNG Accordion panels for easy printing purposes

I've implemented the PrimeNG library's accordion component in my angular project. You can find more information here. In my template, I have some custom css styling for printing the page that looks like this: @media print { .profile-progress ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

Having trouble changing the state within React's useEffect() when using an empty dependencies array? Socket.io is the cause

I have a question regarding the access of allUserMessages from my state within useEffect without anything in its dependency array. Let me provide more details below. Thank you. My goal is to append data to an array in my state using useEffect similar to c ...

Ensuring the structure of a model in a JSON array with Angular

While working with Angular, I have a model defined as follows: export interface MyModel { id: number; content: string; } In one of my services, I fetch JSON data that matches the attributes of MyModel. Here's an example: function getMyModel ...

Utilizing template logic that draws from a fusion of two distinct texts

Looking to display two different texts depending on a boolean value. Here is what I attempted: <div name="health-plans" *ngIf="!flagon"> Test<br />data </div> <div name="health-plans&quo ...

Angular consistently marks form controls as mandatory, even in the absence of validators

Recently, I have been working on this code snippet where I make use of a deepCopy function to ensure that I avoid any unexpected pass by reference issues. const formGroup = this.allowances() formGroup.removeControl('allowanceEndDate') con ...