前言

在前端开发过程中也遇到过一些websocket的坑,所以为了以后不再爬坑,先记录下一些使用方法

1.websocket的url的基础写法

  let url = `ws://${location.host}/ws/socket/io`;
  const socket = new WebSocket(url);

2.https协议下websocket的注意点

需要根据http的协议改变ws前缀

function getWsPrefix() {
    const location = window.location;

    const isHttps = location.protocol === 'https:';
    return isHttps ? 'wss' : 'ws';
}

let url = `${getWsPrefix}://${location.host}/ws/socket/io`;
const socket = new WebSocket(url);

3.基于nginx转发的websocket写法

1.需要添加一个转发代理前缀用于将请求转发到后端,nginx也需要加上相关配置支持websocket

2.需要注意nginx的proxy_read_timeout配置,这是接口请求超时时间,默认60s,nginx也会受影响,需要加心跳解决这个问题

function getWsPrefix() {
    const location = window.location;

    const isHttps = location.protocol === 'https:';
    return isHttps ? 'wss' : 'ws';
}

let url = `${getWsPrefix}://${location.host}/websocket_proxy/ws/socket/io`;
const socket = new WebSocket(url);
# nginx代理转发配置
location /websocket_proxy/ {
  proxy_pass http://minerva-gateway:8080/;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
}