Skip to content

Commit 2f0546e

Browse files
websockets: less verbose
1 parent 23598b0 commit 2f0546e

File tree

1 file changed

+29
-98
lines changed

1 file changed

+29
-98
lines changed

draft_code/modwebsocket_test.py

Lines changed: 29 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,13 @@
22
import ssl
33
import ubinascii
44
from websocket import websocket
5-
import time
65
import select
7-
import gc
8-
9-
# Log memory usage
10-
def log_memory():
11-
gc.collect()
12-
print('Free memory:', gc.mem_free())
13-
14-
# Connect to Wi-Fi (disabled as per your code)
15-
if False:
16-
wlan = network.WLAN(network.STA_IF)
17-
wlan.active(True)
18-
wlan.connect('your_ssid', 'your_password')
19-
while not wlan.isconnected():
20-
pass
21-
print('Connected:', wlan.ifconfig())
226

237
# Resolve hostname
24-
# Option 1: ws.postman-echo.com (recommended for reliable echo)
258
host = 'ws.postman-echo.com'
269
port = 443
2710
handshake_path = '/raw'
28-
# Option 2: echo.websocket.events (unreliable)
11+
# Option: echo.websocket.events (unreliable)
2912
# host = 'echo.websocket.events'
3013
# handshake_path = '/'
3114

@@ -50,16 +33,13 @@ def log_memory():
5033
try:
5134
ssl_sock = ssl.wrap_socket(sock, server_hostname=host)
5235
print('SSL connection established')
53-
print('SSL cipher:', ssl_sock.cipher())
5436
except Exception as e:
5537
print('SSL wrap failed:', e)
5638
sock.close()
5739
raise
58-
log_memory()
5940

6041
# Set socket to non-blocking
6142
ssl_sock.setblocking(False)
62-
print('Socket set to non-blocking')
6343

6444
# Perform WebSocket handshake
6545
key = ubinascii.b2a_base64(b'random_bytes_here').strip()
@@ -73,113 +53,64 @@ def log_memory():
7353
'\r\n'
7454
).format(handshake_path, host, key.decode())
7555

76-
# Send handshake request
7756
try:
78-
bytes_written = ssl_sock.write(handshake.encode())
79-
print('Handshake sent, bytes written:', bytes_written)
80-
print('Handshake request:', handshake)
57+
ssl_sock.write(handshake.encode())
58+
print('Handshake sent')
8159
except Exception as e:
8260
print('Failed to send handshake:', e)
8361
ssl_sock.close()
8462
raise
85-
log_memory()
8663

8764
# Read HTTP response until \r\n\r\n
8865
response_bytes = bytearray()
89-
max_read = 1024
90-
read_timeout = 5 # Increased to 5s for server response
91-
start_time = time.time()
9266
poller = select.poll()
9367
poller.register(ssl_sock, select.POLLIN)
94-
while len(response_bytes) < max_read:
95-
events = poller.poll(100) # Wait 100ms
96-
print('Poll events:', events)
97-
if not events:
98-
if time.time() - start_time > read_timeout:
99-
print('Read timeout reached')
100-
break
101-
continue
102-
try:
68+
max_polls = 50 # 5s timeout (50 * 100ms)
69+
for poll_count in range(max_polls):
70+
if poller.poll(100):
10371
chunk = ssl_sock.read(128)
104-
print('Read attempt, chunk:', chunk)
10572
if chunk is None:
106-
print('Read returned None, continuing to poll')
10773
continue
10874
if not chunk:
109-
print('No more data received (EOF)')
11075
break
111-
print('Received chunk, length:', len(chunk), 'bytes:', chunk)
11276
response_bytes.extend(chunk)
113-
print('Total bytes received:', len(response_bytes))
11477
if b'\r\n\r\n' in response_bytes:
115-
print('End of HTTP headers detected')
116-
http_end = response_bytes.find(b'\r\n\r\n') + 4
117-
if http_end < 4:
118-
ssl_sock.close()
119-
raise Exception('Invalid HTTP response: no headers found')
120-
http_response_bytes = response_bytes[:http_end]
78+
http_response_bytes = response_bytes[:response_bytes.find(b'\r\n\r\n') + 4]
12179
try:
12280
response = http_response_bytes.decode('utf-8')
123-
print('Decoded HTTP response:', response)
81+
if '101 Switching Protocols' not in response:
82+
raise Exception('Handshake failed')
83+
print('Handshake successful')
84+
break
12485
except UnicodeError as e:
125-
print('UnicodeError during decode:', e)
126-
printable = ''.join(c if 32 <= ord(c) < 127 else '.' for c in http_response_bytes.decode('latin-1'))
127-
print('Printable characters:', printable)
86+
print('UnicodeError:', e)
12887
ssl_sock.close()
12988
raise Exception('Failed to decode HTTP response')
130-
if '101 Switching Protocols' not in response:
131-
print('Handshake response:', response)
132-
ssl_sock.close()
133-
raise Exception('Handshake failed')
134-
print('Stopping read to preserve WebSocket frame')
135-
break
136-
except Exception as e:
137-
print('Error reading chunk:', e)
138-
break
139-
log_memory()
140-
141-
# Create WebSocket object
142-
try:
143-
ws = websocket(ssl_sock, True)
144-
print('WebSocket object created')
145-
except Exception as e:
146-
print('Failed to create WebSocket object:', e)
89+
else:
90+
continue
91+
else:
14792
ssl_sock.close()
148-
raise
149-
log_memory()
93+
print('Handshake timeout: No response received after {} seconds ({} bytes received)'.format(max_polls * 0.1, len(response_bytes)))
94+
raise Exception('Handshake timeout')
15095

151-
# Send and receive data with polling
152-
try:
153-
bytes_written = ws.write('Hello, Secure WebSocket!')
154-
print('Sent message, bytes written:', bytes_written)
155-
except Exception as e:
156-
print('Failed to send message:', e)
157-
ws.close()
158-
raise
96+
# Create WebSocket object
97+
ws = websocket(ssl_sock, True)
98+
print('WebSocket object created')
15999

160-
# Poll for data with retries
161-
max_attempts = 10 # Increased retries
162-
poll_timeout = 100 # 100ms per poll
163-
start_time = time.time()
100+
# Send and receive data
101+
ws.write('Hello, Secure WebSocket!')
102+
max_attempts = 5
164103
for attempt in range(max_attempts):
165-
events = poller.poll(poll_timeout)
166-
print('Read poll attempt', attempt + 1, 'events:', events)
167-
if not events:
168-
print('Read attempt', attempt + 1, 'no data available')
169-
if time.time() - start_time > 2: # 2s total timeout
170-
print('Read timeout reached')
171-
break
172-
continue
173-
try:
104+
if poller.poll(100):
174105
data = ws.read(1024)
175-
print('Read attempt', attempt + 1, 'received:', data)
176106
if data:
107+
print('Received:', data)
177108
break
178-
except Exception as e:
179-
print('Read attempt', attempt + 1, 'error:', e)
180-
time.sleep(0.1)
109+
else:
110+
print('Read attempt', attempt + 1, 'no data')
111+
else:
112+
print('Read timeout: No response received after {} attempts ({} seconds)'.format(max_attempts, max_attempts * 0.1))
181113

182114
# Close connection
183115
ws.close()
184116
print('Connection closed')
185-
log_memory()

0 commit comments

Comments
 (0)