javascript - 如何直接连接到本地运行的 WS 服务器实例?
问题描述
我想测试建立在ws
library之上的 WS 服务器。
import { Server as WsServer } from 'ws'
const server = new WsServer({port: 9876})
我以这种方式连接到此服务器以发送消息并接收回复:
const wsClient = new WebSocket('ws://localhost:9876/ws')
我不太喜欢知道在哪个主机和端口服务器上运行。
有没有办法直接连接到这个实例,类似于下面这样,这样服务器就可以独立运行,而不是暴露它的端口?
const server = new WsServer()
const wsClient = new WebSocket(server)
解决方案
为了隐藏端口和/或 ip,您需要设置一个服务器,例如 nginx,并通过代理转发请求:
server {
listen 80;
server_name example.com localhost;
location ~ /ws {
# Here is where you set the port to the application
proxy_pass http://127.0.0.1:9876;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
然后,您可以通过以下方式访问它:
// If you are testing locally make sure "example.com" is in your hosts file
const wsClient = new WebSocket('ws://example.com/ws')
// This will work without a hosts file, but not when in production
const wsClient = new WebSocket('ws://localhost/ws')
如果要使用域而不是localhost
,则需要将其添加到主机文件中:
127.0.0.1 example.com
推荐阅读
- git - 从头创建分支并从先前的提交提交
- reactjs - 如何将访问方法 dispatch() 获取到类的组件中
- javascript - 从 vue 获取文件输入并推送到 Python 代码
- ubuntu - 如何使用 gstreamer 保存带有编码 MPEG4-GENERIC 的 rtsp 音频流
- git - 从 NetBeans IDE 中删除远程 git 标记
- java - 如何在警报对话框中显示选定复选框的列表?
- typescript - OfficeJS 方法回调中的此上下文丢失并且 asyncResult.context 未定义
- flutter - 如何在 Flutter 中使用底部导航项切换 TabBar 的可见性
- python - Django - 网址相互附加
- elasticsearch - Elasticsearch:异常检测是如何工作的(详细)?