封装代码段:
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);
});
展示效果如下: