Engine.IO handler for websocket transport.
774185
def _websocket_handler(self, ws):
        """"""
        # try to set a socket timeout matching the configured ping interval
        for attr in ['_sock', 'socket']:  # pragma: no cover
            if hasattr(ws, attr) and hasattr(getattr(ws, attr), 'settimeout'):
                getattr(ws, attr).settimeout(self.server.ping_timeout)

        if self.connected:
            # the socket was already connected, so this is an upgrade
            self.upgrading = True  # hold packet sends during the upgrade

            pkt = ws.wait()
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.PING or \
                    decoded_pkt.data != 'probe':
                self.server.logger.info(
                    '%s: Failed websocket upgrade, no PING packet', self.sid)
                return []
            ws.send(packet.Packet(
                packet.PONG,
                data=six.text_type('probe')).encode(always_bytes=False))
            self.queue.put(packet.Packet(packet.NOOP))  # end poll

            pkt = ws.wait()
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.UPGRADE:
                self.upgraded = False
                self.server.logger.info(
                    ('%s: Failed websocket upgrade, expected UPGRADE packet, '
                     'received %s instead.'),
                    self.sid, pkt)
                return []
            self.upgraded = True

            # flush any packets that were sent during the upgrade
            for pkt in self.packet_backlog:
                self.queue.put(pkt)
            self.packet_backlog = []
            self.upgrading = False
        else:
            self.connected = True
            self.upgraded = True

        # start separate writer thread
        def writer():
            while True:
                packets = None
                try:
                    packets = self.poll()
                except exceptions.QueueEmpty:
                    break
                if not packets:
                    # empty packet list returned -> connection closed
                    break
                try:
                    for pkt in packets:
                        ws.send(pkt.encode(always_bytes=False))
                except:
                    break
        writer_task = self.server.start_background_task(writer)

        self.server.logger.info(
            '%s: Upgrade to websocket successful', self.sid)

        while True:
            p = None
            try:
                p = ws.wait()
            except Exception as e:
                # if the socket is already closed, we can assume this is a
                # downstream error of that
                if not self.closed:  # pragma: no cover
                    self.server.logger.info(
                        '%s: Unexpected error "%s", closing connection',
                        self.sid, str(e))
                break
            if p is None:
                # connection closed by client
                break
            if isinstance(p, six.text_type):  # pragma: no cover
                p = p.encode('utf-8')
            pkt = packet.Packet(encoded_packet=p)
            try:
                self.receive(pkt)
            except exceptions.UnknownPacketError:  # pragma: no cover
                pass
            except exceptions.SocketIsClosedError:  # pragma: no cover
                self.server.logger.info('Receive error -- socket is closed')
                break
            except:  # pragma: no cover
                # if we get an unexpected exception we log the error and exit
                # the connection properly
                self.server.logger.exception('Unknown receive error')
                break

        self.queue.put(None)  # unlock the writer task so that it can exit
        writer_task.join()
        self.close(wait=False, abort=True)

        return []
836316
def _mksocket(host, port, q, done, stop):
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    attempt = 0
    while not stop.is_set():
        try:
            s.connect((host, port))
            return s
        except Exception as ex:
            # Simple exponential backoff: sleep for 1,2,4,8,16,30,30...
            time.sleep(min(30, 2 ** attempt))
            attempt += 1
578497
async def handler(event):
    """"""
    await asyncio.wait([
        event.delete(),
        event.respond(
            LEARN_PYTHON, reply_to=event.reply_to_msg_id, link_preview=False)
    ])
478793
function log (type) {
    return function(){
      var str = Array.prototype.join.call(arguments, ' ');
      debug('[websocketjs %s] %s', type, str);
    };
  }
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
40278
def packet_in_handler(self, evt):
        """"""
        req_pkt = packet.Packet(evt.msg.data)
        if slow.lacp in req_pkt:
            (req_lacp, ) = req_pkt.get_protocols(slow.lacp)
            (req_eth, ) = req_pkt.get_protocols(ethernet.ethernet)
            self._do_lacp(req_lacp, req_eth.src, evt.msg)
        else:
            self.send_event_to_observers(EventPacketIn(evt.msg))
592831
def http(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(self, event):
            return _handler(self if container is None else container, event, lambda env: func(self, env))
        return handler
    return decorator
1209011
function createTransportServerType() {
    log.info("create transport server type");
    // [ -Events- ]
    // message - a message with transport client source
    // client closed - emitted when a client is closed, with the client
    // close - emitted when the transport is closed
    // error - emitted when the underlying ws has an error
    // listening - emitted when the server is listening
    // [ -Constructor- ]
    function TransportServer() {
        log.info("instantiate transport server");
        // get non-ambiguous this
        var self = this;
        // Call parent constructor
        TransportServer.super_.call(self);
        // Internal structures
        self._ws = undefined;
        self._id = _.uniqueId();
        self._closed = false;
        // state listeners
        self.once('close', function handleClosed() {
            self._closed = true;
        });
        // constructor. return undefined
        return undefined;
    }
    // [ -Inheritance- ]
    util.inherits(TransportServer, events.EventEmitter);
    // [ -Private API- ]
    TransportServer.prototype._handleConnection = function transportServerHandleConnection(wsc) {
        log.info("Transport server handle connection");
        // create a source with send/close
        var source = new ActualTransportClient();
        source.wrap(wsc);
        // proxy events
        source.on('message', this.emit.bind(this, 'message', source));
        source.on('close', this.emit.bind(this, 'client closed', source));
        // Higher layers don't currently need any insight.  If a source
        // has an error, just close it.
        source.on('error', function handleError() {
            source.close();
        });
        // allow chaining
        return this;
    };
    // [ -Public API- ]
    // listen for remote websocket connections
    TransportServer.prototype.listen = function websocketListen(options, cb) {
        log.info("websocket server listen");
        // only allow this to be called once on the object
        if (this._ws) {
            // throw immediately - this is programmer error
            throw new VError("'listen' has already been called on this transport object.");
        }
        // add cb to listeners
        if (cb) {
            this.on('listening', cb);
        }
        // set up websocket server
        this._ws = new ws.Server(options);
        // proxy some events
        // FIXME - be intentional about what errors are passed up
        // at each stage
        this._ws.on('listening', this.emit.bind(this, 'listening'));
        this._ws.on('error', this.emit.bind(this, 'error'));
        this._ws._server.on('close', this.emit.bind(this, 'close'));
        // handle connections from clients
        this._ws.on('connection', this._handleConnection.bind(this));
        // it doesn't make sense to do anything with the object until listen
        // calls back, so return null
        return null;
    };
    // close connection(s)
    TransportServer.prototype.close = function websocketClose() {
        log.info("websocket close");
        if (this._closed) {
            throw new VError("Transport Server has already been closed");
        }
        this._ws.close();
        // it doesn't make sense to do anything with the object
        // after close, so return null
        return null;
    };
    return TransportServer;
}
813855
function WebSocket(socket, ctx) {
  if (!(this instanceof WebSocket))
    return new WebSocket(socket, ctx);

  EventEmitter.call(this);

  this.context = ctx;
  this.socket = socket;
  this.remoteAddress = socket.conn.remoteAddress;
  this.hooks = Object.create(null);
  this.channels = new Map();
  this.auth = false;
  this.filter = null;
  this.prev = null;
  this.next = null;

  this.init();
}
943812
function TransportClient() {
        log.info("instantiate websocket");
        // get non-ambiguous this
        var self = this;
        // Call parent constructor
        TransportClient.super_.call(self);
        // Internal structures
        self._ws = undefined;
        self._id = _.uniqueId(); // debugging tool only
        self._state = "NOT_OPENED";
        // state listeners
        self.once("open", function handleOpened() {
            self._state = "OPEN";
        }).once("close", function handleClosed() {
            self._state = "CLOSED";
        });
        // constructor - return undefined
        return undefined;
    }
1016625
function serveClientOnExpressRoute(app) {


  app.get("/myelements/myelements.jquery.js", function(req, res) {
    //logic taken form socket.io's serveClient
    // var etag = req.headers['if-none-match'];
    // if (etag) {
    //   if (clientVersion == etag) {
    //     debug('serve client 304');
    //     res.writeHead(304);
    //     res.end();
    //     return;
    //   }
    // }
    // debug('serve client source');
    // res.setHeader('ETag', clientVersion);
    res.setHeader("Content-type", "application/javascript");
    var result = Server.client();

    res.send(result);
    //res.sendFile(path.join(__dirname, "client.js"));
  });
}
30779
def handle(self, sock, read_data, path, headers):
        ""
        for i in range(self.attempts):
            try:
                server_sock = eventlet.connect(
                    tuple(random.choice(self.backends)),
                )
            except socket.error:
                eventlet.sleep(self.delay)
                continue
            # Function to help track data usage
            def send_onwards(data):
                server_sock.sendall(data)
                return len(data)
            try:
                size = send_onwards(read_data)
                size += SocketMelder(sock, server_sock).run()
            except socket.error, e:
                if e.errno != errno.EPIPE:
                    raise
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
932688
function wrapNodeSocket(ws, reportError) {
  // Data traveling from websocket to consumer
  var incoming = makeChannel();
  // Data traveling from consumer to websocket
  var outgoing = makeChannel();

  onTake = wrapHandler(onTake, onError);
  outgoing.take(onTake);

  ws.onerror = onError;
  ws.onmessage = wrap(onMessage, onError);
  ws.onclose = wrap(onClose, onError);

  function onError(err) {
    if (reportError) return reportError(err);
    console.error(err.stack);
  }

  function onMessage(evt) {
    if (evt.data instanceof ArrayBuffer) {
      incoming.put(new Uint8Array(evt.data));
    }
  }

  function onClose(evt) {
    incoming.put();
  }

  function onTake(data) {
    // console.log("TAKE", data);
    if (data === undefined) {
      ws.close();
      return;
    }
    ws.send(data);
    outgoing.take(onTake);
  }

  return {
    put: outgoing.put,
    drain: outgoing.drain,
    take: incoming.take,
  };
}
772307
def run(self, handler):
        """"""
        import eventlet.patcher
        if not eventlet.patcher.is_monkey_patched(os):
            msg = ("%s requires eventlet.monkey_patch() (before "
                   "import)" % self.__class__.__name__)
            raise RuntimeError(msg)

        # Separate out wsgi.server arguments
        wsgi_args = {}
        for arg in ('log', 'environ', 'max_size', 'max_http_version',
                    'protocol', 'server_event', 'minimum_chunk_size',
                    'log_x_forwarded_for', 'custom_pool', 'keepalive',
                    'log_output', 'log_format', 'url_length_limit', 'debug',
                    'socket_timeout', 'capitalize_response_headers'):
            try:
                wsgi_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        if 'log_output' not in wsgi_args:
            wsgi_args['log_output'] = not self.quiet

        import eventlet.wsgi
        sock = self.options.pop('shared_socket', None) or self.get_socket()
        eventlet.wsgi.server(sock, handler, **wsgi_args)
521466
function (url) {
            var self = this;
            this._ws = new WebSocket(url);

            // One potential source of confusion: the transport sends two "types" of messages -
            // these are distinct from the protocol's own messages. This is because this transport
            // needs to send an initial "connect" message telling the Brackets side of the transport
            // the URL of the page that it's connecting from, distinct from the actual protocol
            // message traffic. Actual protocol messages are sent as a JSON payload in a message of
            // type "message".
            //
            // Other transports might not need to do this - for example, a transport that simply
            // talks to an iframe within the same process already knows what URL that iframe is
            // pointing to, so the only comunication that needs to happen via postMessage() is the
            // actual protocol message strings, and no extra wrapping is necessary.

            this._ws.onopen = function (event) {
                // Send the initial "connect" message to tell the other end what URL we're from.
                self._ws.send(JSON.stringify({
                    type: "connect",
                    url: global.location.href
                }));
                console.log("[Brackets LiveDev] Connected to Brackets at " + url);
                if (self._callbacks && self._callbacks.connect) {
                    self._callbacks.connect();
                }
            };
            this._ws.onmessage = function (event) {
                console.log("[Brackets LiveDev] Got message: " + event.data);
                if (self._callbacks && self._callbacks.message) {
                    self._callbacks.message(event.data);
                }
            };
            this._ws.onclose = function (event) {
                self._ws = null;
                if (self._callbacks && self._callbacks.close) {
                    self._callbacks.close();
                }
            };
            // TODO: onerror
        }
131877
def wscall(self, method, query=None, callback=None):
        """"""
        if callback is None:
            self.sock.emit(method, query)
        else:
            self.sock.emitack(method, query, callback)