How can I connect to soket on NodeJS and listen to it? that is, the server will act as a client, perhaps there are modules for Nodejs for this, but for some reason I did not find information about it.

  • Speech about simple socket-connection or specifically about websocket? - Dmitriy Simushev
  • About websocket connection - Red Woolf

1 answer 1

For this you can use the module https://www.npmjs.com/package/ws

As written in the documentation example:

var WebSocket = require('ws'); var ws = new WebSocket('ws://echo.websocket.org/', { protocolVersion: 8, origin: 'http://websocket.org' }); ws.on('open', function open() { console.log('connected'); ws.send(Date.now().toString(), {mask: true}); }); ws.on('close', function close() { console.log('disconnected'); }); ws.on('message', function message(data, flags) { console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); setTimeout(function timeout() { ws.send(Date.now().toString(), {mask: true}); }, 500); });