Skip to content

Commit eb40769

Browse files
committed
esp8266/scripts/websocket_helper: Module encapsulating handshake sequences.
1 parent 51dca54 commit eb40769

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)