How to use websockets?


#1

Hello,

I am trying to run a basic exemple from the ws node library doc. Here is the code:

const WebSocket = require('ws')

const ws = new WebSocket(`ws://${process.env.IP}:${process.env.PORT}`)

ws.on('open', function open() {
  ws.send('something')
})

ws.on('message', function incoming(data) {
  console.log(data)
})

ws.on('error', err => console.log(err))

On launching, it crashes with the following error:

{ Error: connect ECONNREFUSED 0.0.0.0:8080
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '0.0.0.0',
  port: 8080 }

I also tried to directly input the address of my workspace instead of ${process.env.IP}:${process.env.PORT}. Then it doesn’t crash but still doesn’t print ‘something’ as I expect it to. By listening to the port 8080, I see a GET request on launching the program.

I’m new to websockets so I may be doing something wrong here, does anyone have a hint on getting this to work?