I need to connect to a external websocket using node JS,but every single tutorial I find online is only about creating server/client and connecting to each other. I already have an external url with a websocket i need to access (even tho it is connected to my network,i have no control over it, so i won't be creating a server or anything like that). It is that simple; Connecting to a external URL using Node JS Websocket/socket.io. So far i have this code, but there is a great chance that it is completely wrong, as im not very experienced in Node JS. So feel free to completely change it. No need to try to upgrade it.
io = require('socket.io-client');
var socket = io.connect('MY.WEBSOCKET.ADDRESS');
function doStuff(){
//Listener
socket.on('connection', function(){
   try {
      console.log('connected!');
   }
});
}
doStuff();
What am i getting wrong?
Since the external server is a plain webSocket server, you can't use a socket.io client to connect to a webSocket server. You would have to use a webSocket client. While socket.io can use webSocket as a transport, it has its own connection layer on top of that and you can't directly connect a socket.io client to a webSocket server. So, you need a plain webSocket client library for nodejs.
Nodejs does not have built-in webSocket support so you can use one of these two libraries on NPM which both have webSocket client support for nodejs:
https://www.npmjs.com/package/websocket
https://www.npmjs.com/package/ws
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With