js服务器上设置运行

js服务器上设置运行

本文介绍了是否可以在node.js服务器上设置运行(服务器端)的socket.io客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两个或多个不同的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.

然后你的用法如下:

var client = require("socket.io-client");
client.connect("http://myendpoint.com:3000/whatever");
client.emit("test", "foo");

一切正常。

所以,谢谢你!

这篇关于是否可以在node.js服务器上设置运行(服务器端)的socket.io客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:55