comunicationLeap/node_modules/engine.io/lib/transports/websocket.js
node_modules/engine.io/lib/transports/websocket.jsRaw
1
2/**
3 * Module dependencies.
4 */
5
6var Transport = require('../transport')
7 , parser = require('engine.io-parser')
8 , debug = require('debug')('engine:ws')
9
10/**
11 * Export the constructor.
12 */
13
14module.exports = WebSocket;
15
16/**
17 * WebSocket transport
18 *
19 * @param {http.ServerRequest}
20 * @api public
21 */
22
23function WebSocket (req) {
24 Transport.call(this, req);
25 var self = this;
26 this.socket = req.websocket;
27 this.socket.on('message', this.onData.bind(this));
28 this.socket.once('close', this.onClose.bind(this));
29 this.socket.on('error', this.onError.bind(this));
30 this.socket.on('headers', function (headers) {
31 self.emit('headers', headers);
32 });
33 this.writable = true;
34};
35
36/**
37 * Inherits from Transport.
38 */
39
40WebSocket.prototype.__proto__ = Transport.prototype;
41
42/**
43 * Transport name
44 *
45 * @api public
46 */
47
48WebSocket.prototype.name = 'websocket';
49
50/**
51 * Advertise upgrade support.
52 *
53 * @api public
54 */
55
56WebSocket.prototype.handlesUpgrades = true;
57
58/**
59 * Advertise framing support.
60 *
61 * @api public
62 */
63
64WebSocket.prototype.supportsFraming = true;
65
66/**
67 * Processes the incoming data.
68 *
69 * @param {String} encoded packet
70 * @api private
71 */
72
73WebSocket.prototype.onData = function (data) {
74 debug('received "%s"', data);
75 Transport.prototype.onData.call(this, data);
76};
77
78/**
79 * Writes a packet payload.
80 *
81 * @param {Array} packets
82 * @api private
83 */
84
85WebSocket.prototype.send = function (packets) {
86 var self = this;
87 for (var i = 0, l = packets.length; i < l; i++) {
88 parser.encodePacket(packets[i], this.supportsBinary, function(data) {
89 debug('writing "%s"', data);
90 self.writable = false;
91 self.socket.send(data, function (err){
92 if (err) return self.onError('write error', err.stack);
93 self.writable = true;
94 self.emit('drain');
95 });
96 });
97 }
98};
99
100/**
101 * Closes the transport.
102 *
103 * @api private
104 */
105
106WebSocket.prototype.doClose = function (fn) {
107 debug('closing');
108 this.socket.close();
109 fn && fn();
110};