0

I am trying to setup a custom keep alive every 5s and attach it to the socket object so that I can reset the timer if there is a communication issue. I think it's more a scoping issue than anything else, but it is a roadblock for me.

client.on('connect', function handleConnection() {
  this.fullDataDec = ''
  this.pingInterval = null
  const credentials = {}
  credentials.player_id = 123
  this.credentials = credentials
  const initPacket = buildPacket(this)

  this.write(initPacket)

  this.pingInterval = setInterval(() => {
    const keepAlivePacket = packetBuilder.buildKeepAlivePacket(this)
    this.write(keepAlivePacket)
  }, 5000)
})

My questions:

  1. this inside of the setInterval refers to the Timeout object. How would I pass my socket (the client object) into this function?
  2. Is it bad practice to pass meta information (like credentials) by adding them as property to the socket object? I thought it's the easiest way especially when I plan to run many sockets.
kentor
  • 16,553
  • 20
  • 86
  • 144
  • Is there a reason that you're not writing this meta information? – Oluwafemi Sule Aug 15 '17 at 23:28
  • @OluwafemiSule do you mean the originally used meta information? I did - for example the credentials. I ommited other properties as it's fairly complex. – kentor Aug 15 '17 at 23:31
  • Ok. I favor emitting an event right after connecting that contains the meta information. [Check this out for more answers](https://stackoverflow.com/questions/4743592/send-additional-data-on-socket-connection) – Oluwafemi Sule Aug 15 '17 at 23:34

0 Answers0