var SocketClient = { websocket: undefined,
strModule: "",
strCommand: "",
parametersObj: {}, OnMessageCallBackFun: undefined,
OnErrorCallBackFun: undefined,
OnOpenCallBackFun: undefined,
OnCloseCallBackFun: undefined,
sendSocket: function() { this.setMessageInnerHTML("module:" + this.strModule); this.setMessageInnerHTML("command:" + this.strCommand); var reqObj = { module: this.strModule,
command: this.strCommand,
parameters: null
};
if (this.strCommand == '' || this.strModule == '') { return false;
}
reqObj.parameters = this.parametersObj;
this.setMessageInnerHTML("parameters:" + JSON.stringify(this.parametersObj));
var json = JSON.stringify(reqObj);
this.setMessageInnerHTML("send:" + json); this.websocket.send(json);
},
setMessageInnerHTML: function(innerHTML) { logInfo(innerHTML);
},
closeWebSocket: function() { this.websocket.close();
},
openWebSocket: function(ip, port) { var that = this;
that.setMessageInnerHTML("开始建立连接-->" + "ws://" + ip + ":" + port);
if ('WebSocket' in window) { that.websocket = new WebSocket("ws://" + ip + ":" + port); } else { that.setMessageInnerHTML("当前浏览器 Not support websocket"); try { return that.OnErrorCallBackFun("当前浏览器 Not support websocket"); } catch (e) {} }
that.websocket.onerror = function () { that.setMessageInnerHTML("WebSocket连接发生错误"); try { return that.OnErrorCallBackFun("WebSocket连接发生错误"); } catch (e) {} };
that.websocket.onopen = function () { that.setMessageInnerHTML("WebSocket连接成功"); try { return that.OnOpenCallBackFun("WebSocket连接成功"); } catch (e) {} };
that.websocket.onmessage = function (event) { console.log(event.data);
that.setMessageInnerHTML("recv<==" + event.data); try { return that.OnMessageCallBackFun(JSON.parse(event.data));
} catch (e) {} };
this.websocket.onclose = function () { that.setMessageInnerHTML("WebSocket连接关闭"); try { return that.OnCloseCallBackFun("WebSocket连接关闭"); } catch (e) {} };
window.onbeforeunload = function () { that.closeWebSocket();
}
}
};
var s = { CallBack: undefined,
Field: 0,
Test: function () { alert("Test: " + this.Field); },
Demo: function () { this.Field = 9;
alert("Demo: " + this.Field); },
Fun: function (ent) { return this.CallBack(ent);
}
};