Start thread to read from stdin, and write to websocket.
 Closes websocket on stdin read errors.

 @param ws [Kontena::Websocket::Client]
 @param tty [Boolean]
 @return [Thread]
542083
def websocket_exec_write_thread(ws, tty: nil)
      Thread.new do
        begin
          if tty
            console_height, console_width = TTY::Screen.size
            websocket_exec_write(ws, 'tty_size' => {
              width: console_width, height: console_height
            })
          end
          read_stdin(tty: tty) do |stdin|
            logger.debug "websocket exec stdin with encoding=#{stdin.encoding}: #{stdin.inspect}"
            websocket_exec_write(ws, 'stdin' => stdin)
          end
          websocket_exec_write(ws, 'stdin' => nil) # EOF
        rescue => exc
          logger.error exc
          ws.close(1001, "stdin read #{exc.class}: #{exc}")
        end
      end
    end
693661
function (ws, message) {
  let clientMessage;

  try {
    clientMessage = JSON.parse(message);
    /* jshint ignore:start */
    if (_.get(clientMessage, 'type') === 'message') {
      ws.send(JSON.stringify({
        ok: true,
        reply_to: _.get(clientMessage, 'id'),
        ts: Date.now(),
        message: _.get(clientMessage, 'text', message),
        type: _.get(clientMessage, 'type', 'message'),
        user: _.get(clientMessage, 'user', 'U1234567'),
        channel: _.get(clientMessage, 'channel', 'C1234567'),
      }));
    }
    /* jshint ignore:end */
  } catch (err) {
    logger.info('Invalid socket data ', message);
  }
}
937046
def _ws_on_close(self, ws: websocket.WebSocketApp):
        
        self.connected = False
        self.logger.error('Websocket closed')
        self._reconnect_websocket()
678102
def send_text(self):
        
        def run(*args):
            """Background process to send the text"""
            self.ws_client.send(json.dumps(self.options).encode('utf8'))

            time.sleep(TEN_MILLISECONDS)

        thread.start_new_thread(run, ())
828108
public static void sendTextBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException {
        sendBlockingInternal(pooledData, WebSocketFrameType.TEXT, wsChannel);
    }
1233577
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
        
        self.logger.error(f'Got error from websocket connection: {str(error)}')
339553
function initClient(client) {
  var ws = client.ws;

  client.state = States.CONNECTING;

  // Wait until we get the user's token so we can finish authorizing
  ws.onmessage = function(msg) {
    var data;
    var info;

    try {
      // Keep track of how much data we receive
      info = client.info();
      if(info) {
        info.bytesReceived += Buffer.byteLength(msg.data, 'utf8');
      }

      data = JSON.parse(msg.data);
    } catch(err) {
      log.error({client: client, err: err}, 'Error parsing client token. Data was `%s`', msg.data);
      ClientInfo.remove(token);
      client.close({
        code: 1011,
        message: 'Error: token could not be parsed.'
      });
      return;
    }

    // Authorize user
    var token = data.token;
    var username = WebsocketAuth.getAuthorizedUsername(token);
    if (!username) {
      log.warn({client: client}, 'Client sent an invalid or expired token (could not get username): token=%s', token);
      ClientInfo.remove(token);
      client.close({
        code: 1008,
        message: 'Error: invalid token.'
      });
      return;
    }

    // Update client details now that he/she is authenticated
    client.id = token;
    client.username = username;
    client.fs = filesystem.create(username);
    ClientInfo.update(client);

    log.info({client: client}, 'Client connected');

    runClient(client);
  };
}
346877
def _footer_start_thread(self, text, time):
        
        footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
        self.top.footer = footerwid
        load_thread = Thread(target=self._loading_thread, args=(time,))
        load_thread.daemon = True
        load_thread.start()
569077
async def start_client(self,
                           sock: anyio.abc.SocketStream,
                           addr,
                           path: str,
                           headers: Optional[List] = None,
                           subprotocols: Optional[List[str]] = None):
        
        self._sock = sock
        self._connection = WSConnection(ConnectionType.CLIENT)
        if headers is None:
            headers = []
        if subprotocols is None:
            subprotocols = []
        data = self._connection.send(
            Request(
                host=addr[0],
                target=path,
                extra_headers=headers,
                subprotocols=subprotocols))
        await self._sock.send_all(data)

        assert self._scope is None
        self._scope = True
        try:
            event = await self._next_event()
            if not isinstance(event, AcceptConnection):
                raise ConnectionError("Failed to establish a connection",
                                      event)
            return event
        finally:
            self._scope = None
1303540
async def open_websocket_server(sock, filter=None):  # pylint: disable=W0622
    
    ws = await create_websocket_server(sock, filter=filter)
    try:
        yield ws
    finally:
        await ws.close()
761599
public static void sendPongBlocking(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel) throws IOException {
        sendBlockingInternal(pooledData, WebSocketFrameType.PONG, wsChannel);
    }
20549
def _run(self, stdout=subprocess.PIPE):
        '''
        
        '''
        assert self._pop is None
        if self._input is not None:
            self._input._run()

        cwd = (self._cwd if self._cwd else os.getcwd()) + '/'

        def glob_or(expr):
            res = [expr]
            if self._expand and ('*' in expr or '?' in expr):
                if expr and expr[0] != '/':
                    expr = cwd + expr
                res = glob.glob(expr)
                if not res:
                    res = [expr]
            return res

        args = [glob_or(arg) for arg in self._args]
        stderr = subprocess.STDOUT if self._err_to_out else None
        assert not self._stdin or self._input is None, "*** ERROR: Stdin must be none outside of head of chain."
        stdin = self._stdin if self._input is None else self._input._pop.stdout
        if stdin is not None and getattr(stdin, 'fileno', None) is None:
            stdin = subprocess.PIPE
        cmd = [self._cmd] + list(itertools.chain.from_iterable(args))
        if self.debug:
            print "*** DEBUG: Run", cmd
        try:
            self._pop = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr,
                                         close_fds=True, cwd=self._cwd, env=self._env)
            if stdin == subprocess.PIPE:
                try:
                    # TODO: Write a non-blocking reader-writer to ship data here
                    self._pop.stdin.write(self._stdin.read())
                except AttributeError:
                    self._pop.stdin.write(self._stdin)
        except OSError:
            print "*** ERROR: %r failed at %r" % (self, self._original_cmd)
            raise
198881
def write( msg )
      $stderr.puts "--> #{msg}" if $DEBUG
      socket.write( msg )
    rescue KJess::NetworkError
      close
      raise
    rescue => e
      close
      raise Error, "Could not write to #{host}:#{port}: #{e.class}: #{e.message}", e.backtrace
    end
17977
public function websocket()
    {
        $this->writeln('Starting swoole websocket server...');

        $ws = new WebsocketServer(
            $this->swooleConfig['ws']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['ws']['port'] ?? self::DEFAULT_SWOOLE_PORT
        );

        $ws->on(
            'open', function ($ws, $request) {
                $this->writeln('client-Connect.');
            }
        );

        $ws->on(
            'message', function ($ws, $frame) {
                $jsonData = JsonHelper::decode($frame->data);
                if (isset($jsonData['handler'])) {
                    $jsonData['swoole_frame'] = $frame;
                    $handlerClass = $jsonData['handler'];
                    try {
                        $ws->push(
                            $frame->fd,
                            Lb::app()->dispatchJob($handlerClass, $jsonData)
                        );
                    } catch (\Throwable $e) {
                        $ws->push(
                            $frame->fd,
                            'Exception:' . $e->getTraceAsString()
                        );
                    }
                } else {
                    $ws->push(
                        $frame->fd,
                        'Handler not exists'
                    );
                }
            }
        );

        $ws->on(
            'close', function ($ws, $fd) {
                $this->writeln('client-closed');
            }
        );

        $ws->start();
    }
840551
def run
      if jruby? || cruby_with_readline?
        set_prompt
        Pry.config.command_prefix = "%"
        logger.info "Launching Adhearsion Console"
        @pry_thread = Thread.current
        pry
        logger.info "Adhearsion Console exiting"
      else
        logger.error "Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must use readline for the console to work."
      end
    end
811199
def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT):
        
        self.ws_client.send(data, opcode)
1328677
def __starttls(self, keyfile=None, certfile=None):
        
        if not self.has_tls_support():
            raise Error("STARTTLS not supported by the server")
        code, data = self.__send_command("STARTTLS")
        if code != "OK":
            return False
        try:
            nsock = ssl.wrap_socket(self.sock, keyfile, certfile)
        except ssl.SSLError as e:
            raise Error("SSL error: %s" % str(e))
        self.sock = nsock
        self.__capabilities = {}
        self.__get_capabilities()
        return True