/**
|
* 服务地址
|
*/
|
let url = "ws://127.0.0.1:5050/";
|
/**
|
* WebSocketClient 客户端
|
*/
|
let WebSocketClient;
|
|
/**
|
* 客户端状态
|
*/
|
let Client = {
|
/**是否连接 */
|
IsOpen: false,
|
/**最新收到的服务端信息 */
|
Receive: null,
|
/**重连检测计时器 */
|
JiShiQi: null,
|
/**打开事件 */
|
OnOpen: null,
|
/**关闭事件 */
|
OnClose: null,
|
/**接收到信息事件 */
|
OnMsg: null,
|
}
|
|
/**
|
* 信息返回类型
|
*/
|
let Result = {
|
Order: "",
|
Time: new Date()
|
};
|
|
/**
|
* 打开连接完成
|
* @param {*} model
|
*/
|
function OnOpen(model) {
|
console.log("打开连接完成");
|
Client.IsOpen = true;
|
|
if (typeof (Client.OnOpen) == 'function') {
|
Client.OnOpen();
|
}
|
}
|
|
/**
|
* 连接断开
|
* @param {*} model
|
*/
|
function OnClose(model) {
|
// console.log("连接断开");
|
Client.IsOpen = false;
|
|
if (typeof (Client.OnClose) == 'function') {
|
Client.OnClose();
|
}
|
}
|
|
/**
|
* 错误
|
* @param {*} error
|
*/
|
function OnError(error) {
|
//console.error(error);
|
}
|
|
/**
|
* 客户端主动向服务端发送消息
|
* @param {String} msg 发送的字符串
|
*/
|
function ClientSendToServerMsg(msg) {
|
if (msg != null && msg.length > 0) {
|
WebSocketClient.send(msg);
|
}
|
}
|
|
/**
|
* 客户端主动向服务端发送实例
|
* @param {Object} obj 对象实例
|
*/
|
function ClientSendToServerObj(obj) {
|
if (null != obj) {
|
var msg = JSON.stringify(obj);
|
WebSocketClient.send(msg);
|
}
|
}
|
|
/**
|
* 数据接收
|
* @param {*} model
|
*/
|
function OnMessage(model) {
|
|
var result = JSON.parse(model.data);
|
console.log(result);
|
|
Client.Receive = result;
|
// Result.Order = result.Order;
|
// Result.Time = new Date();
|
|
// ClientSendToServerObj(Result);
|
|
if (typeof (Client.OnMsg) == 'function') {
|
Client.OnMsg(result);
|
}
|
}
|
|
/**
|
* 打开连接
|
*/
|
function Open() {
|
|
//隔离执行,连接失败后可继续连接
|
(function () {
|
|
//初始化参数
|
Client.IsOpen = false;
|
Client.Receive = null;
|
|
Result.Order = "";
|
Result.Time = new Date();
|
|
if ('WebSocket' in window) {
|
WebSocketClient = new WebSocket(url);
|
}
|
else if ('MozWebSocket' in window) {
|
WebSocketClient = new MozWebSocket(url);
|
}
|
else {
|
alert("浏览器不支持WebSocket");
|
}
|
|
WebSocketClient.onopen = OnOpen;
|
WebSocketClient.onclose = OnClose;
|
WebSocketClient.onerror = OnError;
|
WebSocketClient.onmessage = OnMessage;
|
})();
|
}
|
|
/**
|
* 检测状态
|
*/
|
function Detect() {
|
//已连接
|
if (Client.IsOpen && WebSocketClient.readyState == 1) {
|
//Result.Time = new Date();
|
//ClientSendToServerObj(Result);
|
} else {
|
Open();
|
}
|
// console.log(Client);
|
// console.log(WebSocketClient);
|
}
|
|
|
//启动
|
(function () {
|
Open();
|
Client.JiShiQi = setInterval(Detect, 5000);
|
})()
|