2011-10-26 31 views
0

實現握手我試圖發展握手WebSocket的hybi-17協議http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17)。 根據該草案,我爲客戶機(用戶代理)以下代碼:爲hybi-17

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

和此代碼爲服務器(I跳過插座初始化/管理部分):

$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)); 

現在,下面的例子,從客戶端請求(簡單地用「新MozWebSocket(主機)」呼叫完成):

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 

服務器響應(在本地殼迴盪,作爲調試線):

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

我跟着IETF hybi-17草案規定了什麼,但客戶端請求仍懸而未決並有客戶端和服務器之間沒有真正的聯繫。

怎麼了? 我還需要做些什麼?

在此先感謝。

回答

0

甲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 

消息主體是空的,但應該還有所有標頭經過兩次CRLFs(每個報頭之後的一個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";