wxuns说:
用原生js封装一个websocket客户端
// 封装websocket客户端
function WebSocketClient(url, options) {
this._url = url;
this.options = options;
this._ws = null;
this._init();
}
WebSocketClient.prototype = {
constructor: WebSocketClient,
// 初始化
_init: function() {
var self = this;
self._ws = new WebSocket(self._url);
self._ws.onopen = function(event) {
self.onopen(event);
};
self._ws.onmessage = function(event) {
self.onmessage(event);
};
self._ws.onerror = function(event) {
self.onerror(event);
};
self._ws.onclose = function(event) {
self.onclose(event);
};
},
// 向服务器端发送消息
send: function(data) {
this._ws.send(data);
},
// 关闭websocket连接
close: function() {
this._ws.close();
},
// websocket连接建立时触发
onopen: function(event) {},
// 收到消息时触发
onmessage: function(event) {},
// 连接发生错误时触发
onerror: function(event) {},
// 连接关闭时触发
onclose: function(event) {}
};