如何直接连接到本地运行的WS服务器实例?

时间:2019-07-10 07:56:26

标签: javascript node.js typescript websocket

我想测试在import findspark findspark.init() from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * spark = SparkSession.builder.appName('test').getOrCreate() data = [(1, "siva", 100), (2, "siva2", 200),(3, "siva3", 300),(4, "siva4", 400),(5, "siva5", 500)] schema = ['id', 'name', 'sallary'] df = spark.createDataFrame(data, schema=schema) df.show() library之上构建的WS服务器。

ws

我以这种方式连接到该服务器以发送消息并接收回响应:

import { Server as WsServer } from 'ws'
const server = new WsServer({port: 9876})

我不太想知道在哪个主机和端口服务器上运行。

是否有一种类似于以下示例的直接连接到该实例的方法,以便服务器可以独立运行,而不暴露其端口?

const wsClient = new WebSocket('ws://localhost:9876/ws')

1 个答案:

答案 0 :(得分:0)

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