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

websocket nginx代理存在错误websocket nginx代理必要字段websocket nginx代理错误原因

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连接失败。

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: