2

我正在尝试创建一个基本的 websocket 服务器,服务器从客户端接收握手,但客户端似乎没有接受服务器的握手响应。我对“Sec-WebSocket-Key”也有疑问,我认为散列值太长了!谢谢 :)

 import socket


def handle(s):
    print repr(s.recv(4096))


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

handshakes='\
HTTP/1.1 101 Web Socket Protocol Handshake\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n\
WebSocket-Origin: null\r\n\
WebSocket-Location: ws://localhost:9876/\r\n\
'
def handshake(hs):
    hslist = hs.split('\r\n')
    body = hs.split('\r\n\r\n')[1]
    key = ''
    cc = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

    for h in hslist:
        if h.startswith('Sec-WebSocket-Key:'):
            key = h[19:]
        else:
            continue

    print key

    import hashlib
    import base64
    s = hashlib.sha1()
    s.update(key+cc)
    h = s.hexdigest()
    print 's = ', s
    print 'h = ', h
    return base64.b64encode(h)

while True:
    c,a = s.accept()
    print c
    print a
    msg = c.recv(4096)
    if(msg):

        print msg
        print 'sending handshake ...'
        handshakes += 'Sec-WebSocket-Accept: '+str(handshake(msg))+'\r\n\r\n'
        print handshakes
        c.send(handshakes)
            c.send('Hello !')
            break;

[编辑]

客户 :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Web Socket Example</title>
    <meta charset="UTF-8">
    <script>
      window.onload = function() {
        var s = new WebSocket("ws://localhost:9876/");
        s.onopen = function(e) { alert("opened"); }
        s.onclose = function(e) { alert("closed"); }
        s.onmessage = function(e) { alert("got: " + e.data); }
      };
    </script>
  </head>
    <body>
      <div id="holder" style="width:600px; height:300px"></div>
    </body>
</html>

服务器输出:

<socket._socketobject object at 0xb727bca4>
('127.0.0.1', 46729)
GET / HTTP/1.1
Host: localhost:9876
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:15.0) Gecko/15.0 Firefox/15.0a1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive, Upgrade
Sec-WebSocket-Version: 13
Origin: null
Sec-WebSocket-Key: wZG2EaSH+o/mL0Rr9Efocg==
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket


sending handshake ...
wZG2EaSH+o/mL0Rr9Efocg==
s =  <sha1 HASH object @ 0xb729d660>
h =  49231840aae5a4d6e1488a4b34da39af372452a9
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: null
WebSocket-Location: ws://localhost:9876/
Sec-WebSocket-Accept: NDkyMzE4NDBhYWU1YTRkNmUxNDg4YTRiMzRkYTM5YWYzNzI0NTJhOQ==


handshake sent
4

1 回答 1

2

我认为你需要打电话sha.digest()代替hexdigest(). 您希望将 20 字节的二进制哈希传递给您的 base64 编码器;digest()这样做的同时hexdigest()将这些字节中的每一个转换为 2 字节的十六进制表示。

有关详细信息,请参阅python sha 文档

于 2012-05-10T21:04:10.347 回答