Handle the connection. We only emit the connection event after the proper header was received.
@param $socket
514260
public function handleConnection($socket)
    {
        stream_set_blocking($socket, 0);
        $client = $this->createConnection($socket);

        $timer = $this->loop->addTimer(5, function() use ($client) {
            $client->removeAllListeners('init');
            $client->end('Timeout waiting for PROXY header.');
            $this->emit('proxytimeout', [new Connection($client->stream, $this->loop)]);
        });

        $client->on('init', function($connection) use ($client, $timer) {
            $timer->cancel();
            $this->emit('connection', [$connection]);
        });
    }
669124
public function handleData($socket, $data)
    {
        try
        {
            $this->component->handleMessage($socket->conn, new NetworkMessage($data));
        }
        catch (Error $ex)
        {
            $this->handleError($socket, $ex);
        }
        catch (Exception $ex)
        {
            $this->handleError($socket, $ex);
        }
    }
143018
static function close($socket,$event=null)
    {
        if($event)
        {
            event_del($event);
            event_free($event);
        }
        fclose($socket);
    }
875700
public function handleWsError($e)
    {
        // Pawl pls
        if (strpos($e->getMessage(), 'Tried to write to closed stream') !== false) {
            return;
        }

        $this->logger->error('websocket error', ['e' => $e->getMessage()]);
        $this->emit('error', [$e, $this]);

        $this->handleWsClose(0, 'websocket error');
    }
973854
protected void handleClient(final Socket client) throws IOException {
		final ClientHandler handler = new ClientHandler(client);
		this.executorService.execute(handler);
	}
677021
public function handleConnect()
    {
        $socket = @stream_socket_accept($this->socket);

        if ($socket === false)
        {
            $this->emit('error', [ $this, new ReadException('Socket could not accept new connection.') ]);
            return;
        }

        $client = null;
        $ex = null;

        try
        {
            $client = $this->createClient($socket, [
                'ssl' => $this->config['ssl'],
                'ssl_method' => $this->config['ssl_method'],
            ]);

            $this->emit('connect', [ $this, $client ]);
        }
        catch (Error $ex)
        {}
        catch (Exception $ex)
        {}

        if ($ex !== null)
        {
            $this->handleDisconnect($socket);
            $this->emit('error', [ $this, new ReadException('Socket could not wrap new connection!') ]);
        }
    }
1293842
public function handle(Event $event)
    {
        $name = $event->getName();
        $emitter = $event->getEmitter();
        $emitter->removeListener($name, $this);

        unset($name, $emitter);

        call_user_func_array($this->handler, [$event]);
    }
638580
public function handle($event)
    {
        if ($event instanceof CExceptionEvent)
            $this->logExceptionEvent($event);
        else
            $this->logErrorEvent($event);
        parent::handle($event);
    }
1031294
public function acceptTcp($main_socket) {
        $socket = @stream_socket_accept($main_socket, 0, $remote_address);
        
        //thundering herd EAGAIN (Resource temporarily unavailable)
        if (!$socket) {
            return;
        }
        
        $connection = new Connection($socket, $this);
        
        if($this->handler ){
            $this->handler->attach($connection);
        }
        
        $this->handler->owner = $this;
        
        $this->trigger(Server::ON_ACCEPT, new IOEvent(['context'=>$connection]));
        
        $connection->ready();
    }
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
810820
public function fireEvent(string $event): void
    {
        $this->log->debug('Event {event} has been fired.', ['event' => $event]);
        foreach ($this->event_handlers as $handler) {
            /** @var EventHandler $handler */
            if ($event === $handler->getEvent()) {
                $handler->execute();
            }
        }
    }
58678
public function onMessage(string $message, string $address, SocketInterface $socket)
    {
        try {
            $this->dispatch(Events::MESSAGE, new MessageEvent($socket, $address, $message));
            $socket->send($this->handleQueryFromStream($message), $address);
        } catch (\Exception $exception) {
            $this->dispatch(Events::SERVER_EXCEPTION, new ServerExceptionEvent($exception));
        }
    }
28684
public void run(Socket socket) {
    synchronized (lock) {
      nextSocket = socket;
      lock.notify();
    }
    Thread.yield();
  }
895471
def handle(self, sock, read_data, path, headers):
        ""
        try:
            sock.sendall("HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n" % (self.code, responses.get(self.code, "Unknown")))
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
335981
private function onMessage($msg, $socket) {
        try {
            $payload = @json_decode($msg, true);
            if (!$payload) {
                $this->response($socket, ['error' => 403, 'message' => 'error request']);

                return;
            }
            $command = isset($payload['command']) ? $payload['command'] : 'status';
            $service = isset($payload['args']['service']) ? $payload['args']['service'] : '';
            switch ($command) {
                case 'stop':
                    if ($service) {
                        $rst = $this->stopService($service);
                        $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    } else {
                        $this->response($socket, ['status' => 'done']);
                        $this->shutdown = true;
                        $this->rSignal  = SIGTERM;
                    }
                    break;
                case 'start':
                    if ($service) {
                        $rst = $this->startService($service);
                        $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    } else {
                        $this->response($socket, ['status' => 'fail']);
                    }
                    break;
                case 'reload':
                    $rst = $this->reloadConfig(null, $service);
                    $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    break;
                case 'ps':
                    if ($service) {
                        if (isset($this->services[ $service ])) {
                            $pids = isset($this->services[ $service ]['pids']) ? $this->services[ $service ]['pids'] : [];
                            $this->response($socket, [
                                'ps'   => [$service => $pids],
                                'ssid' => posix_getpid()
                            ]);
                        } else {
                            $this->response($socket, ['ps' => [], 'ssid' => posix_getpid()]);
                        }
                    } else {
                        $ps = [];
                        foreach ($this->services as $s => $ser) {
                            $ps[ $s ] = isset($ser['pids']) ? $ser['pids'] : [];
                        }
                        $this->response($socket, ['ps' => $ps, 'ssid' => posix_getpid()]);
                    }
                    break;
                case 'status':
                default:
                    if ($service) {
                        if (isset($this->services[ $service ])) {
                            $this->response($socket, [
                                'status' => $this->services[ $service ]['status'],
                                'detail' => $this->services[ $service ]
                            ]);
                        } else {
                            $this->response($socket, ['status' => 'unknown', 'detail' => []]);
                        }
                    } else {
                        $this->response($socket, ['status' => 'running', 'services' => $this->services]);
                    }
            }
        } catch (\Exception $e) {
            $this->response($socket, ['error' => 500, 'msg' => $e->getMessage()]);
        }
    }
1311
function afterResponse(Swoole\Request $request, Swoole\Response $response)
    {
        if ($request->isWebSocket())
        {
            $conn = array('header' => $request->header, 'time' => time());
            $this->connections[$request->fd] = $conn;

            if (count($this->connections) > $this->max_connect)
            {
                $this->cleanConnection();
            }

            $this->onWsConnect($request->fd, $request);
        }
        parent::afterResponse($request, $response);
    }
356963
protected function handleReady($data)
    {
        $this->logger->debug('ready packet received');

        // If this is a reconnect we don't want to
        // reparse the READY packet as it would remove
        // all the data cached.
        if ($this->reconnecting) {
            $this->reconnecting = false;
            $this->logger->debug('websocket reconnected to discord through identify');

            return;
        }

        $content = $data->d;
        $this->emit('trace', $data->d->_trace);
        $this->logger->debug('discord trace received', ['trace' => $content->_trace]);

        // Setup the user account
        $this->client    = $this->factory->create(Client::class, $content->user, true);
        $this->sessionId = $content->session_id;

        $this->logger->debug('client created and session id stored', ['session_id' => $content->session_id, 'user' => $this->client->user->getPublicAttributes()]);

        // Private Channels
        $private_channels = new PrivateChannelRepository(
            $this->http,
            $this->cache,
            $this->factory
        );

        if ($this->options['pmChannels']) {
            foreach ($content->private_channels as $channel) {
                $channelPart = $this->factory->create(Channel::class, $channel, true);
                $this->cache->set("pm_channels.{$channelPart->recipient->id}", $channelPart);
                $private_channels->push($channelPart);
            }

            $this->logger->info('stored private channels', ['count' => $private_channels->count()]);
        } else {
            $this->logger->info('did not parse private channels');
        }

        $this->private_channels = $private_channels;

        // Guilds
        $this->guilds = new GuildRepository(
            $this->http,
            $this->cache,
            $this->factory
        );
        $event = new GuildCreate(
            $this->http,
            $this->factory,
            $this->cache,
            $this
        );

        $unavailable = [];

        foreach ($content->guilds as $guild) {
            $deferred = new Deferred();

            $deferred->promise()->then(null, function ($d) use (&$unavailable) {
                list($status, $data) = $d;

                if ($status == 'unavailable') {
                    $unavailable[$data] = $data;
                }
            });

            $event->handle($deferred, $guild);
        }

        $this->logger->info('stored guilds', ['count' => $this->guilds->count()]);

        if (count($unavailable) < 1) {
            return $this->ready();
        }

        // Emit ready after 60 seconds
        $this->loop->addTimer(60, function () {
            $this->ready();
        });

        $function = function ($guild) use (&$function, &$unavailable) {
            if (array_key_exists($guild->id, $unavailable)) {
                unset($unavailable[$guild->id]);
            }

            // todo setup timer to continue after x amount of time
            if (count($unavailable) < 1) {
                $this->logger->info('all guilds are now available', ['count' => $this->guilds->count()]);
                $this->removeListener(Event::GUILD_CREATE, $function);

                $this->setupChunking();
            }
        };

        $this->on(Event::GUILD_CREATE, $function);
    }