一个封装好的websocket的js类,方便进行调用请求处理

该代码段展示了如何使用WebSocket进行实时通信,并管理连接的打开、关闭、错误及消息处理。当连接成功时,会触发回调函数传递'已连接成功'的消息,而当服务器主动断开或通讯出错时,则显示相应的错误信息。此外,还提供了发送数据的方法以及在按钮点击事件中控制执行流程的逻辑。

封装代码段:

var ws = function (wsUrl, wsMsg) {
  var that = this;
  that.Open = function () {
    try {
      if (that.Cache && that.Cache != '') { that.Socket.send(that.Cache); }
      typeof wsMsg == "function" && wsMsg({ msg: "已连接成功" });
    } catch (e) {
      typeof wsMsg == "function" && wsMsg({ msg: "服务器主动断开", end: 1 });
      return false
    }
  };
  that.Close = function () {
    if (that.Socket != undefined && that.Socket.readyState == 1) { that.Socket.close() };
    typeof wsMsg == "function" && wsMsg({ msg: "已断开连接", end: 1 })
  };
  that.Error = function (event) {
    typeof wsMsg == "function" && wsMsg({ msg: "通讯出错", end: 1 })
  };
  that.Message = function (e) {
    typeof wsMsg == "function" && wsMsg(JSON.parse(e.data.replace(/'/g, '"')))
  };
  that.Conn = function () {
    if (that.Socket != undefined && that.Socket.readyState == 1) { return true; }
    try {
      that.Socket = new WebSocket(wsUrl)
    } catch (e) {
      typeof wsMsg == "function" && wsMsg({ msg: "无法连接服务器", end: 1 });
      return false;
    }
    that.Socket.onopen = that.Open;
    that.Socket.onmessage = that.Message;
    that.Socket.onclose = that.Close;
    that.Socket.onerror = that.Error;
    return false;
  };
  that.Send = function (array) {
    that.Cache = JSON.stringify(array);
    if (that.Conn()) { that.Socket.send(that.Cache) }
  };
  that.Conn();
}


 

调用方法如下:

var RunState = $I("RunState"), Btn = $("#SubmitS"), IsRun = 0, ws = new ws("ws://" + window.location.host + "/Keruyun/ProductSync.ashx", function (json) {
  RunState.appendChild(document.createTextNode(json.msg + '\r\n'))
  RunState.scrollTop = (RunState.scrollHeight );
  if (json.end == 1) { Btn.html("开始执行").removeClass("Btn2").addClass("Btn3"); IsRun = 0; }
});

Btn.click(function () {
  if (IsRun != 0) { ws.Send({ Run: 'Stop'}); return; }//发送停止指令

  IsRun = 1; Btn.html("停止执行").removeClass("Btn3").addClass("Btn2");
  let Property = $("input[name='Property']:checked").val();
  if (Property == '') { alert("请选择更新属性项"); return; }

  var SendData = {
    Run:'Start',
    ShopID: $("#ShopID").val(),
    AddT: $("input[name='AddT']:checked").val(),
    Property: $("input[name='Property']:checked").val(),
  };
  ws.Send(SendData);
});

展示效果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值