实现hybi-17的握手



我正试图为websocket hybi-17协议开发握手 (https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-17)。根据该草案,我为客户机(user-agent)编写了以下代码:

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: (.*?)rn#", $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 Protocolsrn" .
  "Upgrade: websocketrn" .
  "Connection: Upgradern" .
  "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草案中的规定,但客户端请求仍然未处理,并且客户端和服务器之间没有真正的连接。

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

HTTP响应定义为:

   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,最后一个额外的CRLF)。

所以你的代码应该是这样的:
$value = 
  "HTTP/1.1 101 Switching Protocolsrn" .
  "Upgrade: websocketrn" .
  "Connection: Upgradern" .
  "Sec-WebSocket-Accept: {$key}rnrn";

相关内容

  • 没有找到相关文章

最新更新