WebSocket Frame Receiver
@constructor
@extends stream.Duplex
548014
function Receiver() {
	stream.Duplex.call(this, {
		readableObjectMode: true
	});

	this._buffer = null;
	this._frame = new Frame();
	this._state = WAITING_FOR_HEADER;
}
556828
function obj(argv, callback) {
  var uri = argv[2];

  if (argv[3]) {
    util.put(argv[2], '<> <> """' + argv[3] + '""" .', function(err, callback){
      if (err) {
        console.error(err);
      } else {
        console.log('put value : ' + argv[3]);
      }
    });
  } else {
    var wss = 'wss://' + uri.split('/')[2] + '/';

    var s = new ws(wss, {
      origin: 'http://websocket.org'
    });

    s.on('open', function open() {
      s.send('sub ' + uri);
    });

    s.on('close', function close() {
      console.log('disconnected');
    });

    s.on('message', function message(data, flags) {
      var a = data.split(' ');
      if (a.length && a[0] === 'pub') {
        util.getAll(a[1], function(err, res) {
          if (err) {
            callback(err);
          } else {
            callback(null, res[res.length-1].object.value);
          }
        });
      }
    });
  }
}
1342741
function createWebSocketTransport(ws) {
  // A transport object.
  var self = new events.EventEmitter();
  // Transport URI contains information like protocol header as query.
  self.uri = ws.upgradeReq.url;
  // Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.
  ws.onmessage = function(event) {
    // `event.data` is a message. It is string if text frame is sent and Buffer if binary frame
    // is sent.
    if (typeof event.data === "string") {
      self.emit("text", event.data);
    } else {
      self.emit("binary", event.data);
    }
  };
  ws.onerror = function(error) {
    self.emit("error", error);
  };
  // A flag to check the transport is opened.
  var opened = true;
  ws.onclose = function() {
    opened = false;
    self.emit("close");
  };
  self.send = function(data) {
    // Allows to send data only it is opened. If not, fires an error.
    if (opened) {
      // If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.
      ws.send(data);
    } else {
      self.emit("error", new Error("notopened"));
    }
    return this;
  };
  self.close = function() {
    ws.close();
    return this;
  };
  return self;
}
639416
function _sendFrameStreamResponse(frame, timeoutMs, responseFrameType) {
        var frameId = xbeeAPI.nextFrameId(),
            sendStream,
            resultStream;

        // Set the frame ID and create the callback to check for it
        frame.id = frameId;

        // Result is the first frame that matches the frame ID and response type
        resultStream = frameSource
            .pipe(rx.operators.filter(_createFilter(frameId, responseFrameType)),
                  rx.operators.takeUntil(rx.timer(timeoutMs)));

        sendStream = rx.Observable.create(function (observer) {
            if (debug) {
                console.log("Debug frame (out):\n", xbeeAPI.buildFrame(frame));
            }

            xbeeAPI.builder.write(frame);
            observer.complete();
        });

        // Return our result stream with a timeout
        return rx.merge(sendStream, resultStream).pipe(
            rx.operators.timeoutWith(timeoutMs, rx.throwError(new Error("Timed out after " + timeoutMs + " ms")))
        );
    }
138112
def send(frame)
      if Frame::Data === frame
        @send_buffer << frame
        if @send_remaining_window < frame.length
          if Stream === self
            connection.callback(:send_deferred, self, frame)
          else
            callback(:send_deferred, self, frame)
          end
        else
          consume_send_buffer
        end
      else
        send_immediately frame
      end
    end
1295653
function chain() {
	let arg = Array.from(arguments),
		pipe = arg.length > 0 ? arg.shift() : stream => stream;

	return function() {
		let writer = through.obj();

		return duplexer(
			{objectMode: true},
			writer,
			pipe.apply(null, [writer].concat(merge(arguments, arg)))
		);
	};
}
589640
function TcpSvrListenFx (err) {
    this.controller.Debug (0,"Hoop fail to listen port: %d ==> %s", this.controller.svcopts.port, err);
    console.log ("### gateway process abort ###");
    process.exit (-1);
}
211737
function OutgoingMessage() {
  // * This is basically a read-only wrapper for the [Stream](protocol/stream.html) class.
  Writable.call(this);

  this._headers = {};
  this._trailers = undefined;
  this.headersSent = false;
  this.finished = false;

  this.on('finish', this._finish);
}
1246561
function FrameWriter(opcode, streamId) {
  if (!opcode) {
    throw new Error('Opcode not provided');
  }
  this.streamId = streamId;
  this.buffers = [];
  this.opcode = opcode;
}
1260979
function(base_url, callback, cors) {
    var recv = new XhrReceiver(base_url + '/chunking_test', {cors: cors});
    var result = 0;
    recv.onmessage = function(e) {
        // Now a cool hack: we can stop receiving after we got at least
        // one chunk, contains some data, but not everyting.
        var l = e.responsetext.split('h\n').length;
        if(e.readystate === 3 && l > 0 && l < 6 ) {
            result = l;
            recv.abort();
        }
    };
    recv.onclose = function(e) {
        recv = recv.onmessage = recv.onclose = null;
        utils.log('Chunking test: ' + (result ? 'passed' : 'failed')
                  + ' (' + result + ' chunk received)');
        callback(!!result);
    };
}
192505
private ChannelFuture writeContinuationFrames(ChannelHandlerContext ctx, int streamId,
            ByteBuf headerBlock, int padding, SimpleChannelPromiseAggregator promiseAggregator) {
        Http2Flags flags = new Http2Flags().paddingPresent(padding > 0);
        int maxFragmentLength = maxFrameSize - padding;
        // TODO: same padding is applied to all frames, is this desired?
        if (maxFragmentLength <= 0) {
            return promiseAggregator.setFailure(new IllegalArgumentException(
                    "Padding [" + padding + "] is too large for max frame size [" + maxFrameSize + "]"));
        }

        if (headerBlock.isReadable()) {
            // The frame header (and padding) only changes on the last frame, so allocate it once and re-use
            int fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
            int payloadLength = fragmentReadableBytes + padding;
            ByteBuf buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
            writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
            writePaddingLength(buf, padding);

            do {
                fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
                ByteBuf fragment = headerBlock.readRetainedSlice(fragmentReadableBytes);

                payloadLength = fragmentReadableBytes + padding;
                if (headerBlock.isReadable()) {
                    ctx.write(buf.retain(), promiseAggregator.newPromise());
                } else {
                    // The frame header is different for the last frame, so re-allocate and release the old buffer
                    flags = flags.endOfHeaders(true);
                    buf.release();
                    buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
                    writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
                    writePaddingLength(buf, padding);
                    ctx.write(buf, promiseAggregator.newPromise());
                }

                ctx.write(fragment, promiseAggregator.newPromise());

                // Write out the padding, if any.
                if (paddingBytes(padding) > 0) {
                    ctx.write(ZERO_BUFFER.slice(0, paddingBytes(padding)), promiseAggregator.newPromise());
                }
            } while (headerBlock.isReadable());
        }
        return promiseAggregator;
    }
416305
function ServerClientStream(app){
    var StreamHandler;
    app.use(function(req, res, next){
      if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){
        var message = req.body;
        message._response = res;
        StreamHandler(message)
      } else {
        return next();
      }
    });
    return {
      send: function(message){
        if(!message._response) throw Error("no response defined");
        var res = message._response;
        message._response = undefined;
        res.json(message);
      },
      listen: function(handler){
        StreamHandler = handler;
      }
    }
  }
114187
function WebsocketBroker(options) {
  // Superclass Constructor
  EventEmitter.call(this);

  options = options || {};
  this.clientsPath = [];
  this.host = options.host || 'localhost';
  this.port = options.port || 8000;
  this.endpoints = options.endpoints || [];
  this.websocketEndpoints = {};

  this.wsServer = null;
  this.httpServer = null;
}
1299263
function wrapNodeSocket(socket, reportError) {
  // Data traveling from node socket to consumer
  var incoming = makeChannel();
  // Data traveling from consumer to node socket
  var outgoing = makeChannel();

  var onDrain2 = wrapHandler(onReadable, onError);
  onTake = wrapHandler(onTake, onError);

  var paused = false;
  var ended = false;

  outgoing.take(onTake);
  socket.on("error", onError);
  socket.on("drain", wrap(onDrain, onError));
  socket.on("readable", wrap(onReadable, onError));
  socket.on("end", wrap(onEnd, onError));

  function onError(err) {
    if (err.code === "EPIPE" || err.code === "ECONNRESET") {
      return onEnd();
    }
    if (reportError) return reportError(err);
    console.error(err.stack);
  }

  function onTake(data) {
    if (ended) return;
    // console.log("TAKE", data);
    if (data === undefined) {
      ended = true;
      return socket.end();
    }
    if (socket.write(data)) {
      outgoing.take(onTake);
    }
    else {
      if (!paused) paused = true;
    }
  }

  function onDrain() {
    if (paused) {
      paused = false;
      outgoing.take(onTake);
    }
  }

  function onEnd() {
    if (ended) return;
    ended = true;
    incoming.put(undefined);
  }

  function onReadable() {
    if (ended) return;
    while (true) {
      var chunk = socket.read();
      // console.log("READ", chunk);
      if (!chunk) return;
      if (!incoming.put(chunk)) {
        incoming.drain(onDrain2);
        return;
      }
    }
  }

  return {
    put: outgoing.put,
    drain: outgoing.drain,
    take: incoming.take,
  };
}
313044
function replayFrame(index) {

        var frame = frames[index];

        // Replay all instructions within the retrieved frame
        for (var i = 0; i < frame.instructions.length; i++) {
            var instruction = frame.instructions[i];
            playbackTunnel.receiveInstruction(instruction.opcode, instruction.args);
        }

        // Store client state if frame is flagged as a keyframe
        if (frame.keyframe && !frame.clientState) {
            playbackClient.exportState(function storeClientState(state) {
                frame.clientState = state;
            });
        }

    }
75479
public static void echoFrame(final WebSocketChannel channel, final StreamSourceFrameChannel ws) throws IOException {

        final WebSocketFrameType type;
        switch (ws.getType()) {
            case PONG:
                // pong frames must be discarded
                ws.close();
                return;
            case PING:
                // if a ping is send the autobahn testsuite expects a PONG when echo back
                type = WebSocketFrameType.PONG;
                break;
            default:
                type = ws.getType();
                break;
        }
        final StreamSinkFrameChannel sink = channel.send(type);
        sink.setRsv(ws.getRsv());
        initiateTransfer(ws, sink, new ChannelListener<StreamSourceFrameChannel>() {
                    @Override
                    public void handleEvent(StreamSourceFrameChannel streamSourceFrameChannel) {
                        IoUtils.safeClose(streamSourceFrameChannel);
                    }
                }, new ChannelListener<StreamSinkFrameChannel>() {
                    @Override
                    public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
                        try {
                            streamSinkFrameChannel.shutdownWrites();
                        } catch (IOException e) {
                            UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                            IoUtils.safeClose(streamSinkFrameChannel, channel);
                            return;
                        }
                        try {
                            if (!streamSinkFrameChannel.flush()) {
                                streamSinkFrameChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(
                                        new ChannelListener<StreamSinkFrameChannel>() {
                                            @Override
                                            public void handleEvent(StreamSinkFrameChannel streamSinkFrameChannel) {
                                                streamSinkFrameChannel.getWriteSetter().set(null);
                                                IoUtils.safeClose(streamSinkFrameChannel);
                                                if (type == WebSocketFrameType.CLOSE) {
                                                    IoUtils.safeClose(channel);
                                                }
                                            }
                                        }, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
                                            @Override
                                            public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {

                                                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                                                IoUtils.safeClose(streamSinkFrameChannel, channel);

                                            }
                                        }
                                ));
                                streamSinkFrameChannel.resumeWrites();
                            } else {
                                if (type == WebSocketFrameType.CLOSE) {
                                    IoUtils.safeClose(channel);
                                }
                                streamSinkFrameChannel.getWriteSetter().set(null);
                                IoUtils.safeClose(streamSinkFrameChannel);
                            }
                        } catch (IOException e) {
                            UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                            IoUtils.safeClose(streamSinkFrameChannel, channel);

                        }
                    }
                }, new ChannelExceptionHandler<StreamSourceFrameChannel>() {
                    @Override
                    public void handleException(StreamSourceFrameChannel streamSourceFrameChannel, IOException e) {
                        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                        IoUtils.safeClose(streamSourceFrameChannel, channel);
                    }
                }, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
                    @Override
                    public void handleException(StreamSinkFrameChannel streamSinkFrameChannel, IOException e) {
                        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                        IoUtils.safeClose(streamSinkFrameChannel, channel);
                    }
                }, channel.getBufferPool()
        );

    }
587642
private void sendHeartbeat(WebSocket websocket) {
        ObjectNode heartbeatPacket = JsonNodeFactory.instance.objectNode();
        heartbeatPacket.put("op", GatewayOpcode.HEARTBEAT.getCode());
        heartbeatPacket.put("d", lastSeq);
        WebSocketFrame heartbeatFrame = WebSocketFrame.createTextFrame(heartbeatPacket.toString());
        nextHeartbeatFrame.set(heartbeatFrame);
        websocket.sendFrame(heartbeatFrame);
    }