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