是否可以在 node.js 服务器上设置运行(服务器端)的 socket.io 客户端? [英] Is it possible to set up a socket.io client running (server-side) on a node.js server?
问题描述
我想在两个或多个不同的 node.js 应用程序服务器之间启用基于套接字的 p2p 通信.我正在使用 socket.io 来处理给定服务器与其所服务的 Web 应用程序之间的所有此类通信 - 但我正在寻找一种服务器到服务器通信的方式.
I'd like to enable socket-based p2p communications between two or more different node.js application servers. I'm using socket.io to handle all such communication between a given server and the web application it serves - but what I'm looking for is a way to communicate server-to-server.
我最初认为它会像这样简单:
I had initially assumed it would be as easy as something like this:
var io = require("socket.io");
var socket = io.connect("my remote endpoint");
然而,事实证明服务器端 socket.io 实现不提供连接"方法,只提供监听方法.
However, as it turns out the server-side socket.io implementation doesn't offer a "connect" method, only a listen method.
这是为什么?为什么我不能将节点应用程序服务器视为在其他地方运行的 socket.io 服务器的客户端?有什么办法可以实现这个功能吗?
Why is this? Why can't I treat a node application server as a client to a socket.io server running elsewhere? Is there any way that I can achieve this functionality?
推荐答案
好的,感谢@pimvdb 在上面的评论中我有了一个可行的解决方案.
OK, so thanks to @pimvdb in the comments above I've got a workable solution.
基本上,npm 安装的 socket.io 库依赖于另一个模块,称为 socket.io-client.在标准的 socket.io 安装中,这将安装在 node_modules/socket.io/node_modules/socket.io-client
Basically, the socket.io library that npm installs has a dependency on another module, called socket.io-client. In a standard socket.io installation this will be installed in node_modules/socket.io/node_modules/socket.io-client
但是,也可以说npm install socket.io-client"并将其安装为自己的一流公民库.
However, it's also possible to say "npm install socket.io-client" and install it as its own first-class citizen library.
那么你的用法是这样的:
Then your usage looks like this:
var client = require("socket.io-client");
var socket = client.connect("http://myendpoint.com:3000/whatever");
socket.emit("test", "foo");
一切正常.
所以,谢谢伙计!
这篇关于是否可以在 node.js 服务器上设置运行(服务器端)的 socket.io 客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!