简体   繁体   中英

How to directly connect to a locally running WS server instance?

I want to test my WS server built on top of ws library .

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

I connect to this server this way to send messages and receive responses back:

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

I don't quite like having to know on which host and port server is running.

Is there a way to directly connect to this instance similar to this below so that server would run in isolation, not exposing its port?

const server = new WsServer()
const wsClient = new WebSocket(server)

In order to hide the port and/or ip, you need to setup a server such as nginx and forward the request through a proxy:

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;
    }
}

You can then access it through:

// 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')

If you are going to use a domain instead of localhost , you need to add it to your hosts file:

127.0.0.1   example.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM