1

I use this code to make a handshake to the client, but in the browser, I get this problem:

Status line does not end with CRLF

You can see that \r\n\r\n is used at the end of the lines, but it's still not working. Where is the problem?

function handshake($client, $headers) {

    //$this->console("Getting client WebSocket version...");
    if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
        $version = $match[1];
    else {
        echo "The client doesn't support WebSocket";
        return false;
    }

    //$this->console("Client WebSocket version is {$version}, (required: 13)");
    if ($version == 13) {
        // Extract header variables
        echo "Getting headers...";
        if (preg_match("/GET (.*) HTTP/", $headers, $match))
            $root = $match[1];
        if (preg_match("/Host: (.*)\r\n/", $headers, $match))
            $host = $match[1];
        if (preg_match("/Origin: (.*)\r\n/", $headers, $match))
            $origin = $match[1];
        if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
            $key = $match[1];

        echo "Client headers are:";
        echo"\t- Root: " . $root;
        echo"\t- Host: " . $host;
        echo"\t- Origin: " . $origin;
        echo"\t- Sec-WebSocket-Key: " . $key;

        echo "Generating Sec-WebSocket-Accept key...";
        $acceptKey = $key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
        $acceptKey = base64_encode(sha1($acceptKey, true));

        $upgrade = "HTTP/1.1 101 Switching Protocols\r\n" .
                "Upgrade: websocket\r\n" .
                "Connection: Upgrade\r\n" .
                "Sec-WebSocket-Accept: $acceptKey" .
                "\r\n\r\n";

        echo "Sending this response to the client"
        . "\r\n" . $upgrade
        ;
        socket_write($client, $upgrade);
        //$client->setHandshake(true);
        echo "Handshake is successfully done!";
        return true;
    }
    else {
        echo
        "WebSocket version 13 required"
        . "(the client supports version {$version})"
        ;
        return false;
    }
}
4

0 回答 0