public function write($buffer)
    {
        $buffer = (string) $buffer;
        $bufLen = Binary::safeStrlen($buffer);

        $socket = $this->getSocket();
        $written = 0;

        while ($written < $bufLen) {
            // PHP's fwrite does not behave nice in regards to errors, so we wrap
            // it with a temporary error handler and treat every warning/notice as
            // a error
            $failed = false;
            $errorMessage = "Failed to write to socket";
            set_error_handler(function ($errno, $errstr) use (&$failed, &$errorMessage) {
                $failed = true;
                $errorMessage .= ": $errstr ($errno)";
            });
            $byteCount = fwrite($socket, Binary::safeSubstr($buffer, $written));
            restore_error_handler();

            if ($byteCount === 0 && defined('HHVM_VERSION')) {
                $failed = true;
            }

            if ($failed || $byteCount === false) {
                throw new \RuntimeException($errorMessage);
            }

            $written += $byteCount;
        }


        return $written;
    }