Creates a main websocket for Discord from a :class:`Client`.

        This is for internal use only.
178527
async def from_client(cls, client, *, shard_id=None, session=None, sequence=None, resume=False):
        
        gateway = await client.http.get_gateway()
        ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None)

        # dynamically add attributes needed
        ws.token = client.http.token
        ws._connection = client._connection
        ws._dispatch = client.dispatch
        ws.gateway = gateway
        ws.shard_id = shard_id
        ws.shard_count = client._connection.shard_count
        ws.session_id = session
        ws.sequence = sequence
        ws._max_heartbeat_timeout = client._connection.heartbeat_timeout

        client._connection._update_references(ws)

        log.info('Created websocket connected to %s', gateway)

        # poll event for OP Hello
        await ws.poll_event()

        if not resume:
            await ws.identify()
            return ws

        await ws.resume()
        try:
            await ws.ensure_open()
        except websockets.exceptions.ConnectionClosed:
            # ws got closed so let's just do a regular IDENTIFY connect.
            log.info('RESUME failed (the websocket decided to close) for Shard ID %s. Retrying.', shard_id)
            return await cls.from_client(client, shard_id=shard_id)
        else:
            return ws
749305
def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        ws.on_pong do |delay|
          # XXX: called with the client mutex locked, do not block
          actor.async.on_pong(delay)
        end

        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # server closed connection
      on_close(exc.code, exc.reason)
      disconnected!

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect or shutdown
      on_error exc
      disconnected!

    rescue => exc
      # XXX: crash instead of reconnecting on unknown errors?
      error exc
      disconnected!

    else
      # impossible: agent closed connection?!
      info "Agent closed connection with code #{ws.close_code}: #{ws.close_reason}"
      disconnected!

    ensure
      ws.disconnect # close socket
    end
803276
def start(self):
        
        if self.running:
            raise RuntimeError("client already running")

        self._main_task = asyncio.ensure_future(
            self._main(),
            loop=self._loop
        )
        self._main_task.add_done_callback(self._on_main_done)
224632
def client(self):
        
        if not hasattr(self, "_client"):
            self._client = connections.get_connection("default")
        return self._client
550914
function Client() {
  EventEmitter.call(this);

  this.debug = false;
  this.socket = dgram.createSocket('udp4');
  this.isSocketBound = false;
  this.devices = {};
  this.port = null;
  this.messagesQueue = [];
  this.sendTimer = null;
  this.discoveryTimer = null;
  this.discoveryPacketSequence = 0;
  this.messageHandlers = [{
    type: 'stateService',
    callback: this.processDiscoveryPacket.bind(this)
  }, {
    type: 'stateLabel',
    callback: this.processLabelPacket.bind(this)
  }, {
    type: 'stateLight',
    callback: this.processLabelPacket.bind(this)
  }];
  this.sequenceNumber = 0;
  this.lightOfflineTolerance = 3;
  this.messageHandlerTimeout = 45000; // 45 sec
  this.resendPacketDelay = 150;
  this.resendMaxTimes = 5;
  this.source = utils.getRandomHexString(8);
  this.broadcastAddress = '255.255.255.255';
}
610954
async def from_client(cls, client, *, resume=False):
        """"""
        gateway = 'wss://' + client.endpoint + '/?v=4'
        ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None)
        ws.gateway = gateway
        ws._connection = client
        ws._max_heartbeat_timeout = 60.0

        if resume:
            await ws.resume()
        else:
            await ws.identify()

        return ws
202771
def client(*args, loop=None, **kwargs):
    
    return _get_default_session(loop=loop).client(*args, **kwargs)
507634
def main(cls):
        
        chain = cls.create()
        args = chain._run_argparser(sys.argv[1:])
        chain._run_chain(sys.stdout, args.dry_run)
        chain._finalize(args.dry_run)
1218815
def main(pub_port=None, sub_port=None):
    '''
    '''
    try:
        if sub_port is None:
            sub_port = get_sub_port()
        if pub_port is None:
            pub_port = get_pub_port()
        context = zmq.Context(1)
        frontend = context.socket(zmq.SUB)
        backend = context.socket(zmq.PUB)

        frontend.bind('tcp://*:{pub_port}'.format(pub_port=pub_port))
        frontend.setsockopt(zmq.SUBSCRIBE, b'')
        backend.bind('tcp://*:{sub_port}'.format(sub_port=sub_port))
        zmq.device(zmq.FORWARDER, frontend, backend)
    except KeyboardInterrupt:
        pass
    finally:
        frontend.close()
        backend.close()
        context.term()
651779
def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # handle known errors, will reconnect
      on_close(exc.code, exc.reason)

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect
      on_close(1006, exc.message)

    rescue => exc
      # TODO: crash instead of reconnecting on unknown errors?
      error exc
      on_close(1006, exc.message)

    else
      # client closed, not going to happen
      on_close(ws.close_code, ws.close_reason)

    ensure
      @ws = nil

      ws.disconnect
    end
62554
function Client (args, options) {
  // Ensure Client instantiated with 'new'
  if (!(this instanceof Client)) {
    return new Client(args, options);
  }

  var servers = []
    , weights = {}
    , regular = 'localhost:11211'
    , key;

  // Parse down the connection arguments
  switch (Object.prototype.toString.call(args)) {
    case '[object Object]':
      weights = args;
      servers = Object.keys(args);
      break;

    case '[object Array]':
      servers = args.length ? args : [regular];
      break;

    default:
      servers.push(args || regular);
      break;
  }

  if (!servers.length) {
    throw new Error('No servers where supplied in the arguments');
  }

  // merge with global and user config
  Utils.merge(this, Client.config);
  Utils.merge(this, options);

  this.servers = servers;
  var compatibility = this.compatibility || this.compatiblity;
  this.HashRing = new HashRing(args, this.algorithm, {
    'compatibility': compatibility,
    'default port': compatibility === 'ketama' ? 11211 : null
  });
  this.connections = {};
  this.issues = [];
}
1205041
def instantiate_client(self, config):
        
        modules = config.module.split('.')
        class_name = modules.pop()
        module_path = '.'.join(modules)

        client_instance = getattr(
            __import__(module_path, {}, {}, ['']),
            class_name
        )()

        client_instance.add_config(config)

        return client_instance
1163909
def start(token, client_id, loop, on_ready_handler=None):
    """"""
    import discord
    import asyncio

    # Create client
    logger.debug("Creating Discord client")
    asyncio.set_event_loop(loop)
    client = discord.Client()
    from . import _client
    _client.client = client

    from .. import datatools
    if datatools.has_data():
        data = datatools.get_data()
    else:
        # Create a blank data file
        data = {"discord": {}}

    # Save default server info to data
    if "servers" not in data["discord"]:
        data["discord"]["servers"] = {}

    # Save default key info to data
    if "keys" not in data["discord"]:
        data["discord"]["keys"] = {}

    # Save logger info to data
    if "log_level" not in data:
        data["log_level"] = "DEBUG"

    data["discord"]["token"] = token
    data["discord"]["client_id"] = client_id
    datatools.write_data(data)

    # Import event handlers
    logger.debug("Importing event handlers")
    event_handlers = _get_event_handlers()

    # Create event handler combiner
    logger.debug("Compiling event handlers")

    def create_event_handler(event_handler_type):
        async def func(*args, **kwargs):
            for module_event_handler in event_handlers[event_handler_type]:
                # Check for errors in the module event
                try:
                    module_event_handler_func = getattr(module_event_handler,
                                                        event_handler_type)
                    await module_event_handler_func(*args, **kwargs)
                except Exception as module_exception:
                    logger.error("An error occured in '{}'".format(module_event_handler))
                    logger.exception(module_exception)

            if on_ready_handler is not None and event_handler_type == "on_ready":
                await on_ready_handler()

        func.__name__ = event_handler_type
        return func

    # Register event handlers
    logger.debug("Registering event handlers into client")
    for event_handler in event_handlers.keys():
        client.event(create_event_handler(event_handler))

    # Run the client loop
    logger.info("Connecting to Discord")
    try:
        client.loop.run_until_complete(client.login(token))
    except Exception as e:
        logger.exception(e)
        logger.critical("Could not connect to Discord")
    else:
        logger.debug("Running the bot")
        try:
            client.loop.run_until_complete(client.connect())
        except KeyboardInterrupt:
            client.loop.run_until_complete(client.logout())
            pending = asyncio.Task.all_tasks(loop=client.loop)
            gathered = asyncio.gather(*pending, loop=client.loop)
            try:
                gathered.cancel()
                client.loop.run_until_complete(gathered)

                # we want to retrieve any exceptions to make sure that
                # they don't nag us about it being un-retrieved.
                gathered.exception()
            except Exception as e:
                logger.exception(e)
        except Exception as e:
            logger.exception(e)
            pending = asyncio.Task.all_tasks(loop=client.loop)
            gathered = asyncio.gather(*pending, loop=client.loop)
            gathered.exception()
        finally:
            try:
                client.loop.run_until_complete(client.logout())
            except Exception as e:
                logger.exception(e)

            logger.critical("Bot stopped\n")
            client.loop.close()
92361
def _start_console(self):
        

        class InputStream:

            def __init__(self):
                self._data = b""

            def write(self, data):
                self._data += data

            @asyncio.coroutine
            def drain(self):
                if not self.ws.closed:
                    self.ws.send_bytes(self._data)
                self._data = b""

        output_stream = asyncio.StreamReader()
        input_stream = InputStream()

        telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True)
        self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console)))

        self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid))
        input_stream.ws = self._console_websocket

        output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n")

        asyncio.async(self._read_console_output(self._console_websocket, output_stream))
576848
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(ES_CORE_ENDPOINT)

    # Get the current node (direct REST GET request)
    print("\nGET g1-test/block/current/_source:")
    response = await client.get('g1-test/block/current/_source')
    print(response)

    # Get the node number 2 with only selected fields (direct REST GET request)
    print("\nGET g1-test/block/2/_source:")
    response = await client.get('g1-test/block/2/_source', {'_source': 'number,hash,dividend,membersCount'})
    print(response)

    # Close client aiohttp session
    await client.close()

    # Create Client from endpoint string in Duniter format
    client = Client(ES_USER_ENDPOINT)

    # prompt entry
    pubkey = input("\nEnter a public key to get the user profile: ")

    # Get the profil of a public key (direct REST GET request)
    print("\nGET user/profile/{0}/_source:".format(pubkey))
    response = await client.get('user/profile/{0}/_source'.format(pubkey.strip(' \n')))
    print(response)

    # Close client aiohttp session
    await client.close()
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();
}
1118796
def _create_connection(self):
        
        transport = SSL if self.ssl else TCP
        return transport(self.server, self.port)