Skip to content

Commit 5331ae9

Browse files
committed
websocket_helper.py: Add websocket helper functions for handshaking.
Authored by @pfalcon.
1 parent 046b8b8 commit 5331ae9

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

websocket_helper.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import sys
2+
try:
3+
import ubinascii as binascii
4+
except:
5+
import binascii
6+
try:
7+
import uhashlib as hashlib
8+
except:
9+
import hashlib
10+
11+
DEBUG = 0
12+
13+
def server_handshake(sock):
14+
clr = sock.makefile("rwb", 0)
15+
l = clr.readline()
16+
#sys.stdout.write(repr(l))
17+
18+
webkey = None
19+
20+
while 1:
21+
l = clr.readline()
22+
if not l:
23+
raise OSError("EOF in headers")
24+
if l == b"\r\n":
25+
break
26+
# sys.stdout.write(l)
27+
h, v = [x.strip() for x in l.split(b":", 1)]
28+
if DEBUG:
29+
print((h, v))
30+
if h == b'Sec-WebSocket-Key':
31+
webkey = v
32+
33+
if not webkey:
34+
raise OSError("Not a websocket request")
35+
36+
if DEBUG:
37+
print("Sec-WebSocket-Key:", webkey, len(webkey))
38+
39+
respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
40+
respkey = hashlib.sha1(respkey).digest()
41+
respkey = binascii.b2a_base64(respkey)[:-1]
42+
43+
resp = b"""\
44+
HTTP/1.1 101 Switching Protocols\r
45+
Upgrade: websocket\r
46+
Connection: Upgrade\r
47+
Sec-WebSocket-Accept: %s\r
48+
\r
49+
""" % respkey
50+
51+
if DEBUG:
52+
print(resp)
53+
sock.send(resp)
54+
55+
56+
# Very simplified client handshake, works for MicroPython's
57+
# websocket server implementation, but probably not for other
58+
# servers.
59+
def client_handshake(sock):
60+
cl = sock.makefile("rwb", 0)
61+
cl.write(b"""\
62+
GET / HTTP/1.1\r
63+
Host: echo.websocket.org\r
64+
Connection: Upgrade\r
65+
Upgrade: websocket\r
66+
Sec-WebSocket-Key: foo\r
67+
\r
68+
""")
69+
l = cl.readline()
70+
# print(l)
71+
while 1:
72+
l = cl.readline()
73+
if l == b"\r\n":
74+
break
75+
# sys.stdout.write(l)

0 commit comments

Comments
 (0)