首页 > 解决方案 > 如何直接连接到本地运行的 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)

标签: javascriptnode.jstypescriptwebsocket

解决方案


为了隐藏端口和/或 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

推荐阅读