|
1 | | -#import network |
2 | 1 | import socket |
| 2 | +import ssl |
3 | 3 | import ubinascii |
4 | 4 | from websocket import websocket |
5 | 5 |
|
| 6 | +# Connect to Wi-Fi |
| 7 | +if False: |
| 8 | + wlan = network.WLAN(network.STA_IF) |
| 9 | + wlan.active(True) |
| 10 | + wlan.connect('your_ssid', 'your_password') |
| 11 | + while not wlan.isconnected(): |
| 12 | + pass |
| 13 | + print('Connected:', wlan.ifconfig()) |
| 14 | + |
| 15 | +# Resolve hostname |
| 16 | +host = 'echo.websocket.events' # Replace with your WSS server |
| 17 | +port = 443 |
| 18 | +try: |
| 19 | + addr_info = socket.getaddrinfo(host, port)[0][-1] |
| 20 | + print('Resolved address:', addr_info) |
| 21 | +except Exception as e: |
| 22 | + print('DNS resolution failed:', e) |
| 23 | + raise |
6 | 24 |
|
7 | 25 | # Create and connect socket |
8 | 26 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
9 | | -#sock.connect(('echo.websocket.org', 80)) |
10 | | -sock.connect(socket.getaddrinfo('echo.websocket.org', 80)[0][-1]) |
11 | | -#getaddrinfo('localhost', 5000)[0][-1] |
| 27 | +try: |
| 28 | + sock.connect(addr_info) |
| 29 | + print('Socket connected') |
| 30 | +except Exception as e: |
| 31 | + print('Connect failed:', e) |
| 32 | + sock.close() |
| 33 | + raise |
| 34 | + |
| 35 | +# Wrap socket with SSL |
| 36 | +try: |
| 37 | + ssl_sock = ssl.wrap_socket(sock, server_hostname=host) |
| 38 | + print('SSL connection established') |
| 39 | +except Exception as e: |
| 40 | + print('SSL wrap failed:', e) |
| 41 | + sock.close() |
| 42 | + raise |
12 | 43 |
|
13 | 44 | # Perform WebSocket handshake |
14 | 45 | key = ubinascii.b2a_base64(b'random_bytes_here').strip() |
15 | 46 | handshake = ( |
16 | 47 | 'GET / HTTP/1.1\r\n' |
17 | | - 'Host: echo.websocket.org\r\n' |
| 48 | + 'Host: {}\r\n' |
18 | 49 | 'Upgrade: websocket\r\n' |
19 | 50 | 'Connection: Upgrade\r\n' |
20 | 51 | 'Sec-WebSocket-Key: {}\r\n' |
21 | 52 | 'Sec-WebSocket-Version: 13\r\n' |
22 | 53 | '\r\n' |
23 | | -).format(key.decode()) |
24 | | -sock.send(handshake.encode()) |
25 | | -response = sock.recv(1024).decode() |
26 | | -print(f"reponse: {response}") |
| 54 | +).format(host, key.decode()) |
| 55 | +ssl_sock.write(handshake.encode()) |
| 56 | +response = ssl_sock.read(1024).decode() |
27 | 57 | if '101 Switching Protocols' not in response: |
28 | | - raise Exception('Handshake failed') |
| 58 | + ssl_sock.close() |
| 59 | + raise Exception('Handshake failed: ' + response) |
29 | 60 |
|
30 | 61 | # Create WebSocket object |
31 | | -ws = websocket(sock, True) |
| 62 | +ws = websocket(ssl_sock, True) |
32 | 63 |
|
33 | 64 | # Send and receive data |
34 | | -ws.write('Hello, WebSocket!') |
| 65 | +ws.write('Hello, Secure WebSocket!') |
35 | 66 | data = ws.read(1024) |
36 | 67 | print('Received:', data) |
37 | 68 |
|
|
0 commit comments