简体   繁体   English

如何使用节点JS连接外部websocket?

[英]How to connect to a external websocket using node JS?

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.我需要使用节点 JS 连接到外部 websocket,但我在网上找到的每个教程都只是关于创建服务器/客户端并相互连接。 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).已经有一个外部 url 和一个 websocket 我需要访问(即使它连接到我的网络,我也无法控制它,所以我不会创建服务器或类似的东西)。 It is that simple;就是这么简单; Connecting to a external URL using Node JS Websocket/socket.io.使用 Node JS Websocket/socket.io 连接到外部 URL。 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.到目前为止,我有这段代码,但很有可能它是完全错误的,因为我在 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.由于外部服务器是普通的 webSocket 服务器,因此您不能使用 socket.io 客户端连接到 webSocket 服务器。 You would have to use a webSocket client.您必须使用 webSocket 客户端。 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. 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 的普通 webSocket 客户端库。

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: Nodejs 没有内置的 webSocket 支持,因此您可以在 NPM 上使用这两个库之一,它们都具有对 nodejs 的 webSocket 客户端支持:

https://www.npmjs.com/package/websocket https://www.npmjs.com/package/websocket

https://www.npmjs.com/package/ws https://www.npmjs.com/package/ws

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM