基本的な 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