6 var Transport = require('../transport')
7 , parser = require('../parser')
8 , util = require('../util')
9 , debug = require('debug')('engine.io-client:websocket');
21 var global = 'undefined' != typeof window ? window : global;
24 * WebSocket transport constructor.
26 * @api {Object} connection options
31 Transport.call(this, opts);
35 * Inherits from Transport.
38 util.inherits(WS, Transport);
46 WS.prototype.name = 'websocket';
54 WS.prototype.doOpen = function(){
62 this.socket = new (ws())(this.uri());
63 this.socket.onopen = function(){
66 this.socket.onclose = function(){
69 this.socket.onmessage = function(ev){
72 this.socket.onerror = function(e){
73 self.onError('websocket error', e);
78 * Writes data to socket.
80 * @param {Array} array of packets.
84 WS.prototype.write = function(packets){
85 for (var i = 0, l = packets.length; i < l; i++) {
86 this.socket.send(parser.encodePacket(packets[i]));
96 WS.prototype.doClose = function(){
97 if (typeof this.socket !== 'undefined') {
103 * Generates uri for connection.
108 WS.prototype.uri = function(){
109 var query = this.query || {};
110 var schema = this.secure ? 'wss' : 'ws';
113 // avoid port if default for schema
114 if (this.port && (('wss' == schema && this.port != 443)
115 || ('ws' == schema && this.port != 80))) {
116 port = ':' + this.port;
119 // append timestamp to URI
120 if (this.timestampRequests) {
121 query[this.timestampParam] = +new Date;
124 query = util.qs(query);
126 // prepend ? to query
131 return schema + '://' + this.host + port + this.path + query;
135 * Feature detection for WebSocket.
137 * @return {Boolean} whether this transport is available.
141 WS.prototype.check = function(){
142 var websocket = ws();
143 return !!websocket && !('__initialize' in websocket && this.name === WS.prototype.name);
147 * Getter for WS constructor.
153 if ('undefined' != typeof process) {
154 return require('ws');
157 return global.WebSocket || global.MozWebSocket;