public function handleConnectedSocks(ConnectionInterface $stream, $host, $port, Deferred $deferred, $uri)
    {
        $reader = new StreamReader();
        $stream->on('data', array($reader, 'write'));

        $stream->on('error', $onError = function (Exception $e) use ($deferred, $uri) {
            $deferred->reject(new RuntimeException(
                'Connection to ' . $uri . ' failed because connection to proxy caused a stream error (EIO)',
                defined('SOCKET_EIO') ? SOCKET_EIO : 5, $e)
            );
        });

        $stream->on('close', $onClose = function () use ($deferred, $uri) {
            $deferred->reject(new RuntimeException(
                'Connection to ' . $uri . ' failed because connection to proxy was lost while waiting for response from proxy (ECONNRESET)',
                defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104)
            );
        });

        if ($this->protocolVersion === 5) {
            $promise = $this->handleSocks5($stream, $host, $port, $reader, $uri);
        } else {
            $promise = $this->handleSocks4($stream, $host, $port, $reader, $uri);
        }

        $promise->then(function () use ($deferred, $stream, $reader, $onError, $onClose) {
            $stream->removeListener('data', array($reader, 'write'));
            $stream->removeListener('error', $onError);
            $stream->removeListener('close', $onClose);

            $deferred->resolve($stream);
        }, function (Exception $error) use ($deferred, $stream, $uri) {
            // pass custom RuntimeException through as-is, otherwise wrap in protocol error
            if (!$error instanceof RuntimeException) {
                $error = new RuntimeException(
                    'Connection to ' . $uri . ' failed because proxy returned invalid response (EBADMSG)',
                    defined('SOCKET_EBADMSG') ? SOCKET_EBADMSG: 71,
                    $error
                );
            }

            $deferred->reject($error);
            $stream->close();
        });
    }