nettoaster
nettoaster

Reputation: 25

Creating multiple WebSocket connections in nodejs in parallel

Hi as in the title I wanna create multiple WebSocket clients in node, so I decided to create a class that would be managing a single connection and then creates an X instance of this class. Here is my code

class CreateNewConnection {
  constructor () {
    this.ws = new WebSocket('wss://echo.websocket.org/', {
      origin: 'https://websocket.org'
    })
    this.ws.on('open', function open () {
      console.log('connected')
      this.ws.send(Date.now())
    })

    this.ws.on('close', function close () {
      console.log('disconnected')
    })

    this.ws.on('message', function incoming (data) {
      console.log(`Roundtrip time: ${Date.now() - data} ms`)

      setTimeout(function timeout () {
        this.ws.send(Date.now())
      }, 500)
    })
  }
}

I am getting an error

  this.ws.send(Date.now())


TypeError: Cannot read property 'send' of undefined

Anybody have any ideas why this isn't working? P.S I am using ws library

Upvotes: 1

Views: 988

Answers (1)

Helgi
Helgi

Reputation: 111

You are trying to call send method from closure. To abolish closure you have 2 ways:

  1. You need to use arrow functions between class's constructor closure and your send method call:

    this.ws.on('message', (data) => {
        console.log(\`Roundtrip time: ${Date.now() - data} ms\`)
        setTimeout(() => {
            this.ws.send(Date.now())
        }, 500)
    })
    
  2. You need to create variable which would refers to class this context:

    constructor () {
        var _this = this;
    // code code code    
    _this.ws.send(Date.now());
    

Here you can read about arrow functions: https://javascript.info/arrow-functions-basics

And here about closures: https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4

TL;DR

Your this.ws.send(Date.now()) refers to timeout function this context, not to class this context.

Upvotes: 1

Related Questions