使用Nginx对Websocket进行反向代理
一. Nginx配置示例
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 6080;
server_name 10.5.30.110;
location ^~ /st-websocket {
proxy_pass http://10.5.17.154:7072/real
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 120s;
proxy_set_header Upgrade websocket;
proxy_set_header Connection Upgrade;
}
}
}
二. html使用实例
<html> <body> <script> var realSocketAddress = "ws://10.5.30.110:6080/st-websocket"; var socketTimeStamp = 1576140668626; var socketAuth = "ce6dfe74b870555d9f2d278cd0a6380d"; openRealWebSocket(); function openRealWebSocket(){ if (window.WebSocket) { realSocket = new WebSocket(realSocketAddress); realSocket.onmessage = function (event) { }; realSocket.onopen = function (event) { //注册 var data = {}; data.type = "REGISTER"; data.timeStamp = socketTimeStamp; data.auth = socketAuth; sendRealSocketMsg(JSON.stringify(data)); }; realSocket.onclose = function (event) { alert("实时数据websocket已关闭"); }; } } function sendRealSocketMsg(message) { if (!window.WebSocket) { return; } if(realSocket){ if (realSocket.readyState == WebSocket.OPEN) { realSocket.send(message); } else { realSocket.close(); } } } </script> </body> </html>