为hybi-17实施握手

时间:2011-10-26 20:12:45

标签: php html5 websocket

我正在尝试为 websocket hybi-17协议http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17)开发握手。 根据该草案,我为客户端(用户代理)制作了以下代码:

var host = 'ws://localhost/server.php';
if ('MozWebSocket' in window) ws = new MozWebSocket (host);
else ws = new WebSocket (host);

和服务器的这段代码(我跳过套接字初始化/管理部分):

$key = $value = null;
preg_match ("#Sec-WebSocket-Key: (.*?)\r\n#", $buffer, $match) && $key = $match[1];
$key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$key = sha1 ($key);
$key = pack ('H*', $key);
$key = base64_encode ($key);

$value = 
  "HTTP/1.1 101 Switching Protocols\r\n" .
  "Upgrade: websocket\r\n" .
  "Connection: Upgrade\r\n" .
  "Sec-WebSocket-Accept: {$key}";

socket_write ($socket, $value, strlen ($value));

现在,按照一个例子,从客户端请求开始(简单地使用'new MozWebSocket(host)'调用):

GET /server.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive, Upgrade
Sec-WebSocket-Version: 8
Sec-WebSocket-Origin: http://localhost
Sec-WebSocket-Extensions: deflate-stream
Sec-WebSocket-Key: oqFCBULD7k+BM41Bc3VEeA==
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket

服务器响应(在本地shell中作为调试行回显):

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: TlKc0Ck7WpqsLhMm/QXABMQWARk=

我遵循了IETF hybi-17草案中指定的内容,但客户端请求仍处于等待状态并且客户端和服务器之间没有真正的连接。

怎么了? 我还需要做些什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

HTTP响应为defined

   Response      = Status-Line               ; Section 6.1
                   *(( general-header        ; Section 4.5
                    | response-header        ; Section 6.2
                    | entity-header ) CRLF)  ; Section 7.1
                   CRLF
                   [ message-body ]          ; Section 7.2

消息正文为空,但在所有标题之后仍然应该有两个CRLF(每个标题后面一个CRLF,最后一个标题后面一个)。

所以你的代码应该是这样的:

$value = 
  "HTTP/1.1 101 Switching Protocols\r\n" .
  "Upgrade: websocket\r\n" .
  "Connection: Upgrade\r\n" .
  "Sec-WebSocket-Accept: {$key}\r\n\r\n";