fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
 
/**
 * Module dependencies.
 */
 
var Transport = require('../transport')
  , parser = require('engine.io-parser')
  , debug = require('debug')('engine:ws')
 
/**
 * Export the constructor.
 */
 
module.exports = WebSocket;
 
/**
 * WebSocket transport 
 *
 * @param {http.ServerRequest}
 * @api public
 */
 
function WebSocket (req) {
  Transport.call(this, req);
  var self = this;
  this.socket = req.websocket;
  this.socket.on('message', this.onData.bind(this));
  this.socket.once('close', this.onClose.bind(this));
  this.socket.on('error', this.onError.bind(this));
  this.socket.on('headers', function (headers) {
    self.emit('headers', headers);
  });
  this.writable = true;
  this.perMessageDeflate = null;
};
 
/**
 * Inherits from Transport.
 */
 
WebSocket.prototype.__proto__ = Transport.prototype;
 
/**
 * Transport name
 *
 * @api public
 */
 
WebSocket.prototype.name = 'websocket';
 
/**
 * Advertise upgrade support.
 *
 * @api public
 */
 
WebSocket.prototype.handlesUpgrades = true;
 
/**
 * Advertise framing support.
 *
 * @api public
 */
 
WebSocket.prototype.supportsFraming = true;
 
/**
 * Processes the incoming data.
 *
 * @param {String} encoded packet
 * @api private
 */
 
WebSocket.prototype.onData = function (data) {
  debug('received "%s"', data);
  Transport.prototype.onData.call(this, data);
};
 
/**
 * Writes a packet payload.
 *
 * @param {Array} packets
 * @api private
 */
 
WebSocket.prototype.send = function (packets) {
  var self = this;
  packets.forEach(function(packet) {
    parser.encodePacket(packet, self.supportsBinary, function(data) {
      debug('writing "%s"', data);
 
      // always creates a new object since ws modifies it
      var opts = {};
      if (packet.options) {
        opts.compress = packet.options.compress;
      }
 
      if (self.perMessageDeflate) {
        var len = 'string' == typeof data ? Buffer.byteLength(data) : data.length;
        if (len < self.perMessageDeflate.threshold) {
          opts.compress = false;
        }
      }
 
      self.writable = false;
      self.socket.send(data, opts, function (err){
        if (err) return self.onError('write error', err.stack);
        self.writable = true;
        self.emit('drain');
      });
    });
  });
};
 
/**
 * Closes the transport.
 *
 * @api private
 */
 
WebSocket.prototype.doClose = function (fn) {
  debug('closing');
  this.socket.close();
  fn && fn();
};