webSocket connection to ‘xx‘ failed: Error during WebSocket handshake: Unexpected response code: 200

webSocket connection to 'xxxx' failed: Error during WebSocket handshake: Unexpected response code: 200

websocket nginx代理存在错误

正确建立websocket连接后,返回状态码101,不会返回200等。

websocket nginx代理必要字段

websocket相关nginx代理内容

http {

    include       mime.types; 
    default_type  application/octet-stream;
    
    # 重要
    map $http_upgrade $connection_upgrade {
      default upgrade;
      '' close;
    }
    # 使用了Nginx的map指令,根据请求头中的“Upgrade”字段值
    # 判断是否需要升级HTTP连接为WebSocket连接
    # 如果没有的话,nginx代理配置websocket会报错
    
    sendfile        on;
    #tcp_nopush     on;
    
    #keepalive_timeout  0;
    keepalive_timeout  65;
    
    #gzip  on;

    server {
        listen       9091;
        server_name  localhost;

	 location /gameflow/ws/chat/ {
            root   html;
            index  index.html index.htm;
            proxy_pass http://127.0.0.1:8000/gameflow/ws/chat/;
            proxy_http_version 1.1;
            proxy_connect_timeout 30s;
            proxy_read_timeout 60s;
            proxy_send_timeout 30s;
            
            # 重要
            proxy_set_header Upgrade $http_upgrade;  
            proxy_set_header Connection $connection_upgrade;
            # 在HTTP报头中添加Upgrade和Connection字段
            # 以使Nginx将普通HTTP请求升级为WebSocket连接  
            
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

       
    }

websocket nginx代理错误原因

     因为在进行WebSocket握手时,
     客户端和服务器之间需要通过HTTP请求和响应来协商和确认建立WebSocket连接。
     如果代理服务器(如Nginx)未正确设置Upgrade和Connection字段,并将其传递给后端Websocket服务器,
     则可能会导致服务器认为客户端不支持WebSocket连接,
     从而返回错误的响应码(如400 Bad Request、404 Not Found等),从而导致WebSocket连接失败。
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值