You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.2 KiB
68 lines
2.2 KiB
define(function () {
|
|
function Socket(params) {
|
|
this.params = params;
|
|
this.url = (window.location.protocol === 'http:' ? 'ws' : 'wss') + '://' + window.location.hostname;
|
|
this.port = params.port || '';
|
|
this.params = '';
|
|
if (params.params.constructor.toString().indexOf('Object') !== -1) {
|
|
// for (var key in params.params) {
|
|
// if (Object.hasOwnProperty.call(params.params, key)) {
|
|
// this.params += (this.params ? '&' : '') + key + '=' + params.params[key];
|
|
// }
|
|
// }
|
|
this.params = Object.keys(params.params).map(function (key) {
|
|
return key + '=' + params.params[key];
|
|
}).join('&');
|
|
}
|
|
this.connect(params);
|
|
}
|
|
|
|
Socket.prototype.connect = function (params) {
|
|
var self = this;
|
|
this.ws = new WebSocket(this.url + (this.port ? ':' + this.port : '') + (this.params ? '?' + this.params : ''));
|
|
this.ws.onopen = function () {
|
|
self.heartbeat();
|
|
if (typeof params.onopen === 'function') {
|
|
params.onopen();
|
|
}
|
|
};
|
|
this.ws.onmessage = function (event) {
|
|
var data = JSON.parse(event.data);
|
|
self.heartbeat();
|
|
if (typeof params.onmessage === 'function') {
|
|
params.onmessage(data);
|
|
}
|
|
};
|
|
this.ws.onclose = function () {
|
|
self.connect(self.params);
|
|
if (typeof params.onclose === 'function') {
|
|
params.onclose();
|
|
}
|
|
};
|
|
this.ws.onerror = function () {
|
|
|
|
};
|
|
};
|
|
|
|
Socket.prototype.heartbeat = function () {
|
|
var self = this;
|
|
clearTimeout(this.timeoutId);
|
|
this.timeoutId = setTimeout(function () {
|
|
self.send({
|
|
type: 'ping'
|
|
});
|
|
}, 3000);
|
|
};
|
|
|
|
Socket.prototype.send = function (params) {
|
|
if (this.ws.readyState === 1) {
|
|
this.ws.send(typeof params === 'string' ? params : JSON.stringify(params));
|
|
}
|
|
};
|
|
|
|
Socket.prototype.close = function (params) {
|
|
this.ws.close();
|
|
};
|
|
|
|
return Socket;
|
|
}); |