Wraps the WebRTC socket inside a channel to encapsulate the join-request protocol while allowing application-defined control protocols to be multiplexed
516704
function Channel (id, socket) {
  var log = debug('webrtc-tree-overlay:channel(' + id + ')')
  this._log = log
  var self = this
  this.id = id
  this._socket = socket
    .on('data', function (data) {
      log('received data:')
      log(data.toString())
      var message = JSON.parse(data)
      if (message.type === 'DATA') {
        log('data: ' + message.data)
        self.emit('data', message.data)
      } else if (message.type === 'JOIN-REQUEST') {
        log('join-request: ' + JSON.stringify(message))
        self.emit('join-request', message)
      } else {
        throw new Error('Invalid message type on channel(' + id + ')')
      }
    })
    .on('connect', function () {
      self.emit('connect', self)
    })
    .on('close', function () {
      log('closing')
      self.emit('close')
    })
    .on('error', function (err) {
      log(err.message)
      log(err.stack)
    })
}
383585
def wrap_handler(cls, handler, protocol, **kwargs):
        '''  '''
        def _wrapper(request, *args, **kwargs):
            instance = cls(request=request, **kwargs)
            if protocol == Resource.Protocol.http:
                return instance._wrap_http(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.websocket:
                return instance._wrap_ws(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.amqp:
                return instance._wrap_amqp(view_type, *args, **kwargs)
            else:
                raise Exception('Communication protocol not specified')
        return _wrapper
547716
def make_socket():
    '''
    '''
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_IP), socket.INADDR_ANY)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', MCAST_PORT))
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    sock.settimeout(0.2)
    return sock
1234468
private void prepSocketChannel(SocketChannel sc) {
        try {
            sc.socket().setSendBufferSize(1024 * 1024 * 2);
            sc.socket().setReceiveBufferSize(1024 * 1024 * 2);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
584562
private TransportChannelHandler createChannelHandler(Channel channel, RpcHandler rpcHandler) {
    TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
    TransportClient client = new TransportClient(channel, responseHandler);
    TransportRequestHandler requestHandler = new TransportRequestHandler(channel, client,
      rpcHandler, conf.maxChunksBeingTransferred());
    return new TransportChannelHandler(client, responseHandler, requestHandler,
      conf.connectionTimeoutMs(), closeIdleConnections, this);
  }
727507
function wrap() {
  var ports = this.compiledModule.ports;

  var incomingEmitter = new EventEmitter();
  var outgoingEmitter = new EventEmitter();

  var emit = incomingEmitter.emit.bind(incomingEmitter);

  Object.keys(ports).forEach(function(key) {
    outgoingEmitter.addListener(key, function() {
      var args = Array.prototype.slice.call(arguments)

      ports[key].send.apply(ports[key], args);
    });

    if (ports[key].subscribe) {
      ports[key].subscribe(function() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(key);

        emit.apply(incomingEmitter, args);
      });
    }
  });

  incomingEmitter.emit = outgoingEmitter.emit.bind(outgoingEmitter);;

  this.emitter = incomingEmitter;
  this.ports = this.compiledModule.ports;
}
321693
function ServerChannel(server, opts) {
  opts = opts || {};
  events.EventEmitter.call(this);

  this.server = server;
  this._endWritable = !!utils.getOption(opts, 'endWritable', true);
  this._prefix = normalizedPrefix(opts.scope);

  var cache = server._cache;
  var svc = server.service;
  var hash = svc.hash;
  if (!cache[hash]) {
    // Add the channel's protocol to the cache if it isn't already there. This
    // will save a handshake the first time on channels with the same protocol.
    cache[hash] = new Adapter(svc, svc, hash);
  }
  this._adapter = null;

  this.destroyed = false;
  this.draining = false;
  this.pending = 0;
  this.once('_eot', function (pending, err) {
    debug('server channel EOT');
    this.emit('eot', pending, err);
  });
}
744060
private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
        ByteBuf out = null;
        ChannelPromise promise = null;
        ByteBufAllocator alloc = ctx.alloc();
        boolean needUnwrap = false;
        ByteBuf buf = null;
        try {
            final int wrapDataSize = this.wrapDataSize;
            // Only continue to loop if the handler was not removed in the meantime.
            // See https://github.com/netty/netty/issues/5860
            outer: while (!ctx.isRemoved()) {
                promise = ctx.newPromise();
                buf = wrapDataSize > 0 ?
                        pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) :
                        pendingUnencryptedWrites.removeFirst(promise);
                if (buf == null) {
                    break;
                }

                if (out == null) {
                    out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount());
                }

                SSLEngineResult result = wrap(alloc, engine, buf, out);

                if (result.getStatus() == Status.CLOSED) {
                    buf.release();
                    buf = null;
                    promise.tryFailure(SSLENGINE_CLOSED);
                    promise = null;
                    // SSLEngine has been closed already.
                    // Any further write attempts should be denied.
                    pendingUnencryptedWrites.releaseAndFailAll(ctx, SSLENGINE_CLOSED);
                    return;
                } else {
                    if (buf.isReadable()) {
                        pendingUnencryptedWrites.addFirst(buf, promise);
                        // When we add the buffer/promise pair back we need to be sure we don't complete the promise
                        // later in finishWrap. We only complete the promise if the buffer is completely consumed.
                        promise = null;
                    } else {
                        buf.release();
                    }
                    buf = null;

                    switch (result.getHandshakeStatus()) {
                        case NEED_TASK:
                            if (!runDelegatedTasks(inUnwrap)) {
                                // We scheduled a task on the delegatingTaskExecutor, so stop processing as we will
                                // resume once the task completes.
                                break outer;
                            }
                            break;
                        case FINISHED:
                            setHandshakeSuccess();
                            // deliberate fall-through
                        case NOT_HANDSHAKING:
                            setHandshakeSuccessIfStillHandshaking();
                            // deliberate fall-through
                        case NEED_WRAP:
                            finishWrap(ctx, out, promise, inUnwrap, false);
                            promise = null;
                            out = null;
                            break;
                        case NEED_UNWRAP:
                            needUnwrap = true;
                            return;
                        default:
                            throw new IllegalStateException(
                                    "Unknown handshake status: " + result.getHandshakeStatus());
                    }
                }
            }
        } finally {
            // Ownership of buffer was not transferred, release it.
            if (buf != null) {
                buf.release();
            }
            finishWrap(ctx, out, promise, inUnwrap, needUnwrap);
        }
    }
1004779
function clientNetworkData(channelDefArray, opt) {
	var self = {
		__TYPE__ : MessageType.CS_NET,
		channelCount : new type.UInt32Le( function () {
			return self.channelDefArray.obj.length;
		}),
		channelDefArray : channelDefArray || new type.Factory( function (s) {
			self.channelDefArray = new type.Component([]);
			
			for (var i = 0; i < self.channelCount.value; i++) {
				self.channelDefArray.obj.push(channelDef().read(s));
			}
		})
	};
	
	return new type.Component(self, opt);
}
269648
protected ChannelFuture handleHandshake(ChannelHandlerContext ctx, NettyHttpRequest req, WebSocketBean<?> webSocketBean, MutableHttpResponse<?> response) {
        int maxFramePayloadLength = webSocketBean.messageMethod().flatMap(m -> m.getValue(OnMessage.class, "maxPayloadLength", Integer.class)).orElse(65536);
        WebSocketServerHandshakerFactory wsFactory =
                new WebSocketServerHandshakerFactory(
                        getWebSocketURL(ctx, req),
                        null,
                        true,
                        maxFramePayloadLength
                );
        handshaker = wsFactory.newHandshaker(req.getNativeRequest());
        MutableHttpHeaders headers = response.getHeaders();
        io.netty.handler.codec.http.HttpHeaders nettyHeaders;
        if (headers instanceof NettyHttpHeaders) {
            nettyHeaders = ((NettyHttpHeaders) headers).getNettyHeaders();
        } else {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, List<String>> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        }
        Channel channel = ctx.channel();
        if (handshaker == null) {
            return WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel);
        } else {
            return handshaker.handshake(
                    channel,
                    req.getNativeRequest(),
                    nettyHeaders,
                    channel.newPromise()
            );
        }
    }
380097
def websocket(
        self, uri, host=None, strict_slashes=None, subprotocols=None, name=None
    ):
        
        self.enable_websocket()

        # Fix case where the user did not prefix the URL with a /
        # and will probably get confused as to why it's not working
        if not uri.startswith("/"):
            uri = "/" + uri

        if strict_slashes is None:
            strict_slashes = self.strict_slashes

        def response(handler):
            async def websocket_handler(request, *args, **kwargs):
                request.app = self
                if not getattr(handler, "__blueprintname__", False):
                    request.endpoint = handler.__name__
                else:
                    request.endpoint = (
                        getattr(handler, "__blueprintname__", "")
                        + handler.__name__
                    )
                try:
                    protocol = request.transport.get_protocol()
                except AttributeError:
                    # On Python3.5 the Transport classes in asyncio do not
                    # have a get_protocol() method as in uvloop
                    protocol = request.transport._protocol
                ws = await protocol.websocket_handshake(request, subprotocols)

                # schedule the application handler
                # its future is kept in self.websocket_tasks in case it
                # needs to be cancelled due to the server being stopped
                fut = ensure_future(handler(request, ws, *args, **kwargs))
                self.websocket_tasks.add(fut)
                try:
                    await fut
                except (CancelledError, ConnectionClosed):
                    pass
                finally:
                    self.websocket_tasks.remove(fut)
                await ws.close()

            self.router.add(
                uri=uri,
                handler=websocket_handler,
                methods=frozenset({"GET"}),
                host=host,
                strict_slashes=strict_slashes,
                name=name,
            )
            return handler

        return response
1308054
function CBSocketWrapper(config) {

    this.config = config;

    var self = this;

    // Connection status flag
    this.connected = false;

    // Socket Wrapper listeners
    this.on('connect', function() {
        self.connected = true;
        logger.info('Connected to Continuum Bridge', self.config.cbSocket);
    });
    this.on('connecting', function() {
        self.connected = false;
        logger.info('Connecting..');
    });
    this.on('error', function(error) {
        self.connected = false;
        logger.log('Error', error);
    });
    this.on('disconnect', function() {
        self.connected = false;
        logger.info('Disconnected from Continuum Bridge:', self.config.cbSocket);
    });
}
935990
function WebSocket(url, opt_protocols) {
    var scope = ctorEvent();
    goog.base(this, descriptor);

    /**
     * Underlying WS.
     * @type {!WebSocket}
     * @private
     */
    this.handle_ = arguments.length == 1 ?
        new originalWs(url) :
        new originalWs(url, opt_protocols);

    /**
     * Event type trackers, by name.
     * @type {!Object.<Function>}
     * @private
     */
    this.trackers_ = {};

    /**
     * Properties, accumulated during setup before send().
     * @type {!Object}
     * @private
     */
    this.props_ = {
      'url': url,
      'protocol': opt_protocols
    };

    wtf.trace.Scope.leave(scope);
  }
1003191
function enableRerouting() {
  if (enabled)
    return;
  enabled = true;

  const connect = Net.Socket.prototype.connect;
  Net.Socket.prototype.connect = function(options, callback) {
    const hasNormalizedArgs = Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(options).length > 0;
    const isNode8           = Array.isArray(options) && hasNormalizedArgs;
    if (isNode8) {
      const reroutedOptions = rerouteOptions(options[0]);
      callback              = options[1];
      return connect.call(this, reroutedOptions, callback);
    } else if (typeof options === 'object') {
      const reroutedOptions = rerouteOptions(options);
      return connect.call(this, reroutedOptions, callback);
    } else
      return connect.apply(this, arguments);
  };
}
696362
private void configureSsl(SocketChannel ch) {
        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
    }
90953
function Channel_connect(cb) {
  cb = utils.callOnce(cb)

  var websocket = new WebSocket(this._url, [this._protocol])

  websocket.addEventListener("open",    onOpen)
  websocket.addEventListener("message", onMessage)
  websocket.addEventListener("close",   onClose)
  websocket.addEventListener("error",   onError)

  var channel = this

  //-----------------------------------
  function onOpen() {
    channel._websocket = websocket

    cb(null)
  }

  //-----------------------------------
  function onMessage(event) {
    if (!channel._websocket) return

    var message = JSON.parse(event.data)

    channel.emit("message", message)
  }

  //-----------------------------------
  function onClose() {
    if (!channel._websocket) return

    channel._websocket = null

    channel.emit("close")
    cb(new Error("closed"))
  }

  //-----------------------------------
  function onError() {
    channel.emit("error", new Error("undisclosed error"))
  }

}
363559
def _connection_handler(self, event_name, data, channel_name):
        
        if channel_name in self.channels:
            self.channels[channel_name]._handle_event(event_name, data)