我正在尝试创建一个基本的 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 Handshakern
Upgrade: WebSocketrn
Connection: Upgradern
WebSocket-Origin: nullrn
WebSocket-Location: ws://localhost:9876/rn
'
def handshake(hs):
hslist = hs.split('rn')
body = hs.split('rnrn')[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))+'rnrn'
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
我认为您需要调用sha.digest()
来代替hexdigest()
。 您希望将 20 字节二进制哈希传入 base64 编码器; digest()
执行此操作,同时hexdigest()
将这些字节中的每一个转换为 2 字节十六进制表示形式。
有关详细信息,请参阅 python sha 文档。