簡體   English   中英

python websocket handshake(RFC 6455)

[英]python websocket handshake (RFC 6455)

我正在嘗試使用RFC 6455協議在python上實現一個簡單的websoket服務器。 我從這里這里采取握手格式。

我使用Chromium 17和Firefox 11作為客戶端,並收到此錯誤:

Uncaught Error: INVALID_STATE_ERR: DOM Exception 11

我希望在我的瀏覽器中看到hello from server hello from client並在服務器日志中hello from client看到hello from server

我猜我的握手是錯的,你能指出我的錯誤嗎?

服務器日志,請求:

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8999
Origin: null
Sec-WebSocket-Key: 8rYWWxsBPEigeGKDRNOndg==
Sec-WebSocket-Version: 13

服務器日志,響應:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=

原始字符串響應:

HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: 3aDXXmPbE5e9i08zb9mygfPlCVw=\r\n\r\n

服務器代碼:

import socket
import re
from base64 import b64encode
from hashlib import sha1

websocket_answer = (
    'HTTP/1.1 101 Switching Protocols',
    'Upgrade: websocket',
    'Connection: Upgrade',
    'Sec-WebSocket-Accept: {key}\r\n\r\n',
)

GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8999))
s.listen(1)

client, address = s.accept()
text = client.recv(1024)
print text

key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text)
    .groups()[0]
    .strip())

response_key = b64encode(sha1(key + GUID).digest())
response = '\r\n'.join(websocket_answer).format(key=response_key)

print response
client.send(response)

print client.recv(1024)
client.send('hello from server')

客戶代碼:

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript">
        var s = new WebSocket('ws://127.0.0.1:8999');
        s.onmessage = function(t){alert(t)};
        s.send('hello from client');
    </script>
</head>
<body>
</body>
</html>

您的服務器握手代碼看起來不錯

客戶端代碼看起來會在(異步)握手完成之前嘗試發送消息。 您可以通過將消息發送到websocket的onopen方法來避免這種情況。

建立連接后,服務器不會以純文本形式發送或接收消息。 有關詳細信息,請參閱規范的數據框架部分。 (客戶端代碼可以忽略這一點,因為瀏覽器會為您處理數據框架。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM