2012-10-14 47 views
7

嘗試爲Python3支持的應用程序創建Web前端。該應用程序將需要雙向流媒體,這聽起來像是一個很好的機會來看待websockets。Python 3中的Websocket實現

我的第一個傾向是使用已經存在的東西,mod-pywebsocket的示例應用程序已被證明是有價值的。不幸的是,他們的API似乎不容易擴展,它是Python2。

環顧博客圈,許多人爲早期版本的websocket協議編寫了​​自己的websocket服務器,但大多數人並沒有實現安全密鑰哈希,所以不工作。

閱讀RFC 6455我決定去捅它自己,想出了以下內容:

#!/usr/bin/env python3 

""" 
A partial implementation of RFC 6455 
http://tools.ietf.org/pdf/rfc6455.pdf 
Brian Thorne 2012 
""" 

import socket 
import threading 
import time 
import base64 
import hashlib 

def calculate_websocket_hash(key): 
    magic_websocket_string = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 
    result_string = key + magic_websocket_string 
    sha1_digest = hashlib.sha1(result_string).digest() 
    response_data = base64.encodestring(sha1_digest) 
    response_string = response_data.decode('utf8') 
    return response_string 

def is_bit_set(int_type, offset): 
    mask = 1 << offset 
    return not 0 == (int_type & mask) 

def set_bit(int_type, offset): 
    return int_type | (1 << offset) 

def bytes_to_int(data): 
    # note big-endian is the standard network byte order 
    return int.from_bytes(data, byteorder='big') 


def pack(data): 
    """pack bytes for sending to client""" 
    frame_head = bytearray(2) 

    # set final fragment 
    frame_head[0] = set_bit(frame_head[0], 7) 

    # set opcode 1 = text 
    frame_head[0] = set_bit(frame_head[0], 0) 

    # payload length 
    assert len(data) < 126, "haven't implemented that yet" 
    frame_head[1] = len(data) 

    # add data 
    frame = frame_head + data.encode('utf-8') 
    print(list(hex(b) for b in frame)) 
    return frame 

def receive(s): 
    """receive data from client""" 

    # read the first two bytes 
    frame_head = s.recv(2) 

    # very first bit indicates if this is the final fragment 
    print("final fragment: ", is_bit_set(frame_head[0], 7)) 

    # bits 4-7 are the opcode (0x01 -> text) 
    print("opcode: ", frame_head[0] & 0x0f) 

    # mask bit, from client will ALWAYS be 1 
    assert is_bit_set(frame_head[1], 7) 

    # length of payload 
    # 7 bits, or 7 bits + 16 bits, or 7 bits + 64 bits 
    payload_length = frame_head[1] & 0x7F 
    if payload_length == 126: 
     raw = s.recv(2) 
     payload_length = bytes_to_int(raw) 
    elif payload_length == 127: 
     raw = s.recv(8) 
     payload_length = bytes_to_int(raw) 
    print('Payload is {} bytes'.format(payload_length)) 

    """masking key 
    All frames sent from the client to the server are masked by a 
    32-bit nounce value that is contained within the frame 
    """ 
    masking_key = s.recv(4) 
    print("mask: ", masking_key, bytes_to_int(masking_key)) 

    # finally get the payload data: 
    masked_data_in = s.recv(payload_length) 
    data = bytearray(payload_length) 

    # The ith byte is the XOR of byte i of the data with 
    # masking_key[i % 4] 
    for i, b in enumerate(masked_data_in): 
     data[i] = b^masking_key[i%4] 

    return data 

def handle(s): 
    client_request = s.recv(4096) 

    # get to the key 
    for line in client_request.splitlines(): 
     if b'Sec-WebSocket-Key:' in line: 
      key = line.split(b': ')[1] 
      break 
    response_string = calculate_websocket_hash(key) 

    header = '''HTTP/1.1 101 Switching Protocols\r 
Upgrade: websocket\r 
Connection: Upgrade\r 
Sec-WebSocket-Accept: {}\r 
\r 
'''.format(response_string) 
    s.send(header.encode()) 

    # this works 
    print(receive(s)) 

    # this doesn't 
    s.send(pack('Hello')) 

    s.close() 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
s.bind(('', 9876)) 
s.listen(1) 

while True: 
    t,_ = s.accept() 
    threading.Thread(target=handle, args = (t,)).start() 

使用這個基本的測試頁(與MOD-pywebsocket作品):

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Web Socket Example</title> 
    <meta charset="UTF-8"> 
</head> 
<body> 
    <div id="serveroutput"></div> 
    <form id="form"> 
     <input type="text" value="Hello World!" id="msg" /> 
     <input type="submit" value="Send" onclick="sendMsg()" /> 
    </form> 
<script> 
    var form = document.getElementById('form'); 
    var msg = document.getElementById('msg'); 
    var output = document.getElementById('serveroutput'); 
    var s = new WebSocket("ws://"+window.location.hostname+":9876"); 
    s.onopen = function(e) { 
     console.log("opened"); 
     out('Connected.'); 
    } 
    s.onclose = function(e) { 
     console.log("closed"); 
     out('Connection closed.'); 
    } 
    s.onmessage = function(e) { 
     console.log("got: " + e.data); 
     out(e.data); 
    } 
    form.onsubmit = function(e) { 
     e.preventDefault(); 
     msg.value = ''; 
     window.scrollTop = window.scrollHeight; 
    } 
    function sendMsg() { 
     s.send(msg.value); 
    } 
    function out(text) { 
     var el = document.createElement('p'); 
     el.innerHTML = text; 
     output.appendChild(el); 
    } 
    msg.focus(); 
</script> 
</body> 
</html> 

這會接收數據並將其正確掩蓋,但我無法使傳輸路徑正常工作。

作爲測試寫「你好」的插座,上面的程序計算出的字節將被寫入到所述插座爲:

['0x81', '0x5', '0x48', '0x65', '0x6c', '0x6c', '0x6f'] 

匹配其中在RFC的section 5.7給出的十六進制值。不幸的是,該框架在Chrome的開發者工具中從未出現過。

任何想法我失蹤?還是一個當前正在運行的Python3 websocket示例?

+0

Tornado支持websockets和Python 3. http://www.tornadoweb.org/documentation/websocket.html –

+0

謝謝托馬斯。我想首先有一個獨立的實現 - 這與理解協議和爲我解決問題一樣。看看[龍捲風源代碼](https://github.com/facebook/tornado/blob/master/tornado/websocket.py),我看到一個頭部** Sec-WebSocket-Protocol **正在從服務器到客戶端,但[spec](http://tools.ietf.org/html/rfc6455#section-4.2.2)表示這是可選的。 – Hardbyte

+0

如果一個客戶端請求一個子協議,服務器需要回應它(總是假定它支持子協議)。不這樣做會導致握手錯誤,所以這可能與您的消息發送問題無關。 – simonc

回答

7

當我嘗試從Safari瀏覽器6.0.1對獅子說你的Python代碼,我得到

Unexpected LF in Value at ... 

在JavaScript控制檯。我也從Python代碼中得到了一個IndexError異常。

當我從獅子座的Chrome版本24.0.1290.1開始討論您的python代碼時,我沒有收到任何Javascript錯誤。在您的JavaScript onopen()onclose()方法被稱爲,但不是onmessage()。 python代碼不會拋出任何異常,並且看起來有接收消息併發送了它的響應,也就是您看到的行爲。

由於Safari瀏覽器不喜歡在你的頭結尾的LF我試着刪除它,即

header = '''HTTP/1.1 101 Switching Protocols\r 
Upgrade: websocket\r 
Connection: Upgrade\r 
Sec-WebSocket-Accept: {}\r 
'''.format(response_string) 

當我做出這個改變Chrome可以看到您的回覆信息即

got: Hello 

出現在JavaScript控制檯中。

Safari仍然不起作用。現在,當我嘗試發送消息時,會引發另一個問題。

websocket.html:36 INVALID_STATE_ERR: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable. 

無JavaScript的WebSocket的事件處理程序的不斷火,我仍然看到從蟒蛇的IndexError例外。

總之。由於頭部響應中存在額外的LF,因此您的Python代碼不適用於Chrome。還有其他一些事情正在進行,因爲與Chrome工作的代碼不適用於Safari。

我已經計算出潛在的問題,現在有更新的例子在Safari和Chrome的工作。

base64.encodestring()總是增加一個尾隨\n它的回報。這是Safari正在抱怨的LF的來源。

請撥打.strip(),返回值爲calculate_websocket_hash,並使用您的原始標題模板在Safari和Chrome上正常工作。

+0

真棒,後刪除現在適用於Firefox和Chrome的額外CRLF。 – Hardbyte