Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created May 10, 2012 03:36
Show Gist options
  • Save yongboy/2650889 to your computer and use it in GitHub Desktop.
Save yongboy/2650889 to your computer and use it in GitHub Desktop.
socket.io client websocket 片段
(function (exports, io, global) {
exports.websocket = WS;
function WS (socket) {
io.Transport.apply(this, arguments);
};
io.util.inherit(WS, io.Transport);
WS.prototype.name = 'websocket';
WS.prototype.open = function () {
var query = io.util.query(this.socket.options.query)
, self = this
, Socket
if (!Socket) {
Socket = global.MozWebSocket || global.WebSocket;
}
this.websocket = new Socket(this.prepareUrl() + query);
this.websocket.onopen = function () {
self.onOpen();
self.socket.setBuffer(false);
};
this.websocket.onmessage = function (ev) {
self.onData(ev.data);
};
this.websocket.onclose = function () {
self.onClose();
self.socket.setBuffer(true);
};
this.websocket.onerror = function (e) {
self.onError(e);
};
return this;
};
WS.prototype.send = function (data) {
this.websocket.send(data);
return this;
};
WS.prototype.payload = function (arr) {
for (var i = 0, l = arr.length; i < l; i++) {
this.packet(arr[i]);
}
return this;
};
WS.prototype.close = function () {
this.websocket.close();
return this;
};
WS.prototype.onError = function (e) {
this.socket.onError(e);
};
WS.prototype.scheme = function () {
return this.socket.options.secure ? 'wss' : 'ws';
};
WS.check = function () {
return ('WebSocket' in global && !('__addTask' in WebSocket))
|| 'MozWebSocket' in global;
};
WS.xdomainCheck = function () {
return true;
};
io.transports.push('websocket');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
, this
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment