ws 链接使用

文章介绍了如何在JavaScript中使用WebSocket进行创建、初始化、重连以及事件处理,包括onopen、onmessage、onclose和onerror。

使用ws

import QueryWebSocket from "websocket";
// 创建webSocket
    createWebSocket() {
      this.webSocket = new QueryWebSocket({
        url: `wss://websocket/ws/notice/`,
        createSuccess: () => { },
        queryData: (res) => {
          console.log(res);
          // 执行操作
        },
      })
    },

webSocket.js 封装文件

// 创建构造函数
const QueryWebSocket = function (obj1) {
  let obj = obj1 || {};
  const defaultObj = {
    url: "",
    lockReconnect: false,
    ws: "",
    tt: "",
    timeout: 30000,
    timeoutObj: null,
  };
  this.config = Object.assign(defaultObj, obj);
  if ("WebSocket" in window) {
    console.log("支持WebSocket");
    const that = this;
    setTimeout(function () {
      that.createWebSocket();
    }, 1000);
  } else {
    alert("该浏览器不支持WebSocket");
  }
};
QueryWebSocket.prototype = {
  QueryWebSocket: QueryWebSocket,
  reset: function () {
    clearTimeout(this.config.timeoutObj);
    this.config.ws.onclose();
  },
  start: function () {
    const that = this;
    this.config.timeoutObj = setInterval(function () {
      let message = "I";
      that.config.ws.send(message); // 启动心跳
    }, 15000);
  },
  // 创建webSocket
  createWebSocket: function () {
    try {
      // 成功
      this.config.ws = new WebSocket(this.config.url);
      this.webSocketInit(); // 初始化webSocket连接函数
      // this.config.createSuccess();
    } catch (e) {
      // 失败
      console.log("catch",e.message);
      // 重连函数
      this.webSocketReconnect(this.config.url);
    }
  },
  // 向websocket发送信息
  sendContent: function (data) {
    this.config.ws.send(JSON.stringify(data));
  },
  // 初始化方法,成功后执行
  webSocketInit: function () {
    const that = this;
    // 连接关闭函数
    that.config.ws.onclose = function () {
      console.log("连接已关闭...",new Date());
      clearTimeout(that.config.timeoutObj);
      that.webSocketReconnect(that.config.url) // 如果连接关闭则重连
    };
    // 连接错误函数
    that.config.ws.onerror = function () {
      console.log("连接错误...",new Date());
      that.webSocketReconnect(that.config.url); // 如果连接错误则重连
    };
    // 连接建立,发送信息
    that.config.ws.onopen = function () {
      console.log("链接成功",new Date());
      that.config.lockReconnect = false;
      that.config.ws.send("I");
      that.start(); // 订阅业务发送之后启动心跳检测机制
    };
    // 业务订阅成功后接受服务端推送消息,其实是个字符串
    that.config.ws.onmessage = function (evt) {
      if (evt.data !== "O") {
        if (JSON.parse(evt.data).content !== "PONG") {
          that.config.queryData(JSON.parse(evt.data));
        }
      }
    };
  },
  // 重连
  webSocketReconnect: function (url) {
    const that = this;
    console.log("socket 连接断开,正在尝试重新建立连接");
    if (that.config.lockReconnect) {
      return;
    }
    that.config.lockReconnect = true;
    that.config.tt && clearTimeout(that.config.tt);
    that.config.tt = setTimeout(function () {
      that.createWebSocket(url);
    }, 4000);
  },
};
export default QueryWebSocket;

WebSocket连接配置方法可从服务器端配置和客户端配置两方面来看。 服务器端配置方面,有以下几种情况: - **Nginx配置**:要配置服务器块,将相应的服务器块(server)配置添加到Nginx设置中,指定正确的服务器名(server_name)以及监听的端口(通常80用于HTTP或443用于HTTPS),在该服务器块中添加location块,以处理特定路径(例如/ws)的Websocket连接请求。示例配置如下: ```nginx server { listen 80; server_name your_websocket_server.com; location /ws { proxy_pass http://websocket_backend; # 转发到后端WebSocket服务 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; # 当使用Websocket时,通常您需要适合的超时设置 proxy_read_timeout 7d; # 设置较高的读取超时时间 } } ``` 若WebSocket服务器运行在不同的主机或端口上,确保proxy_pass指向正确的地址,还可调整超时时间的配置,如proxy_read_timeout设置到更长的时间,以避免连接过早关闭 [^2]。 - **Springboot配置**:在使用https的情况下,配置服务器https域名,可参考Nginx配置多个ssl域名项目,将路径的ws替换成wss,路径改为域名。例如: ```javascript // 替换前 websocket = new WebSocket("ws://localhost:8082/websocket"); // 替换后 websocket = new WebSocket("wss://www.abc.com/websocket"); ``` [^3] 客户端配置方面,在使用C/C++创建并连接到WebSocket服务器时,需先创建Native C++工程,在源文件中封装相关接口,然后在ArkTS层调用封装好的接口,使用hilog或console.info等方法将日志打印到控制台或生成设备日志 [^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值