我使用此代码与客户端进行握手,但在浏览器中,我遇到了这个问题:
状态行不以CRLF结尾
您可以看到\r\n\r\n
在行尾使用,但它仍无效。问题在哪里?
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;
}
}