页面代码:
socketUrl = "ws://" + location.host + "/websocket/ws?uid=1";
// location.host即前端服务部署地址
var socket = new WebSocket(socketUrl);
// 打开事件
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("这是来自客户端的消息" + location.href + new Date());
};
// 获得消息事件
socket.onmessage = function(msg) {
console.log(msg?.data, 140);
};
// 关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
// 发生了错误事件
socket.onerror = function() {
console.log("发生了错误");
};
devserver 跨域代理配置
"/websocket": {
target: 'ws://10.180.145.228:12345',
ws: true,
changeOrigin: true,
logLevel: 'debug',
secure: false,
pathRewrite: {
"^/websocket": ""
}
},
或者nginx 代理配置
http {
upstream sdwan_ws{
server 10.180.146.79:9999;
}
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/yourdomain.log;
location / {
root html;
index index.html index.htm;
}
}
location /websocket {
proxy_pass http://sdwan_ws;
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
add_header Access-Control-Allow-Origin *;
proxy_set_header Upgrade websocket;
proxy_set_header Connection Upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /websocket/(.*) /$1 break;
}
}
最重要的就是在反向代理的配置中增加了如下两行,其它的部分和普通的HTTP反向代理没有任何差别
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
设置后会在HTTP的请求中多了如下头部:
Upgrade: websocket
Connection: Upgrade
表示请求服务器升级协议为WebSocket。
当状态未101时连接成功