k8w / tsrpc

A TypeScript RPC framework, with runtime type checking and serialization, support both HTTP and WebSocket. It is very suitable for website / APP / games, and absolutely comfortable to full-stack TypeScript developers.
MIT License
1.9k stars 203 forks source link

请问如何让http和websocket使用同一端口 #40

Closed Riceneeder closed 2 years ago

Riceneeder commented 2 years ago

如题,目前实现的项目需要两种协议,但不想使用两个端口

k8w commented 2 years ago

可以前置 nginx 解决,例如(nginx 配置):

# https 和 wss
server {
    server_name xxx.cn;

    listen 443 ssl;
    ssl on;
    ssl_certificate /etc/nginx/cert/k8w.cn.pem; 
    ssl_certificate_key /etc/nginx/cert/k8w.cn.key;

    # https (Server 是 http)
    location /match-server/ {
        proxy_set_header  Access-Control-Allow-Origin *;
        proxy_pass http://127.0.0.1:3200;
    }

    # wss (Server 是 ws)
    location /room-server/1/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://127.0.0.1:3201;
    }

}

# http 和 ws
server {
    server_name xxx.cn;

    listen 80;

    # http (Server 是 http) 跟上面一样
    location /match-server/ {
        proxy_set_header  Access-Control-Allow-Origin *;
        proxy_pass http://127.0.0.1:3200;
    }

    # ws (Server 是 ws) 跟上面一样
    location /room-server/1/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://127.0.0.1:3201;
    }

}
Riceneeder commented 2 years ago

Thanks