1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- 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;
- });
|