我用PHP编写websocket服务器/客户端,它在2年内为我工作。现在,它不工作,他说:Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value
WebSocket握手期间出现错误:PHP中错误的'Sec-WebSocket-Accept'标头值
我的客户方代码基本上是这样的:
socket = new WebSocket("ws://<?= EVENT_SERVER_ADDR ?>:"+EVENT_SERVER_PORT+"<?= EVENT_SERVER_WWW_PATH ?>");
PHP服务器端的代码是这样的:
list ($resource, $host, $connection, $version, $origin, $key, $protocol, $upgrade) = $this->getheaders ($buffer);
$this->log ("Handshaking...");
$reply =
"HTTP/1.1 101 Switching Protocols\r\n" .
"Upgrade: {$upgrade}\r\n" .
"Connection: {$connection}\r\n" .
"Sec-WebSocket-Version: {$version}\r\n" .
"Sec-WebSocket-Origin: {$origin}\r\n" .
"Sec-WebSocket-Location: ws://{$host}{$resource}\r\n" .
"Sec-WebSocket-Accept: " . $this->calcKey ($key) . "\r\n";
if ($protocol)
$reply .= "Sec-WebSocket-Protocol: $protocol\r\n";
$reply .= "\r\n";
// Closes the handshake
socket_write ($user->socket, $reply, strlen ($reply));
function calcKey ($key) {
// Constant string as specified in the ietf-hybi-17 draft
$key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$key = sha1 ($key, true);
// $key = pack ('H*', $key); // should I uncomment this line?
$key = base64_encode ($key);
return $key;
}
function getheaders ($buffer) {
$resource = $host = $connection = $version = $origin = $key = $protocol = $upgrade = null;
preg_match ('#GET (.*?) HTTP#', $buffer, $match) && $resource = $match[1];
preg_match ("#Host: (.*?)\r\n#", $buffer, $match) && $host = $match[1];
preg_match ("#Connection: (.*?)\r\n#", $buffer, $match) && $connection = $match[1];
preg_match ("#Sec-WebSocket-Version: (.*?)\r\n#", $buffer, $match) && $version = $match[1];
preg_match ("#Origin: (.*?)\r\n#", $buffer, $match) && $origin = $match[1];
preg_match ("#Sec-WebSocket-Key:\s*(.*?)\r\n#", $buffer, $match) && $key = $match[1];
preg_match ("#Sec-WebSocket-Protocol:\s*(.*?)\r\n#", $buffer, $match) && $protocol = $match[1];
preg_match ("#Upgrade: (.*?)\r\n#", $buffer, $match) && $upgrade = $match[1];
return array ($resource, $host, $connection, $version, $origin, $key, $protocol, $upgrade);
}
这很有趣,那些家伙只是改变了标准无保持旧的代码运作,并且不要在网上说任何事情(我真的试图很努力地谷歌)。有谁知道我的问题是什么?
嗨,这是失败与不同的浏览器?明显的问题,但你没有指定它。 – pietro909
@ pietro909 Chrome 41失败,Firefox表示:“Firefox无法建立到服务器的连接ws://192.168.1.34:38848/operator/modules/campaign/event_server.php” –
@ pietro909 MacOS下的Safari 10.9说:“[错误] WebSocket连接到'ws://192.168.1.34:38848/operator/modules/campaign/event_server.php'失败:标头值(campaign.php,第0行)中的UTF-8序列无效” –