Skip to content

Commit 25a7aa3

Browse files
improve websocket
1 parent 6f3bc13 commit 25a7aa3

File tree

1 file changed

+32
-22
lines changed

1 file changed

+32
-22
lines changed

draft_code/modwebsocket_test.py

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
print('Connected:', wlan.ifconfig())
1414

1515
# Resolve hostname
16-
host = 'echo.websocket.events' # Replace with your WSS server
16+
host = 'echo.websocket.events'
1717
port = 443
1818
try:
1919
addr_info = socket.getaddrinfo(host, port)[0][-1]
@@ -63,23 +63,26 @@
6363
ssl_sock.close()
6464
raise
6565

66-
# Read response in chunks with debugging
66+
# Read HTTP response until \r\n\r\n
6767
response_bytes = bytearray()
6868
max_read = 1024 # Maximum bytes to read
69-
read_timeout = 10 # Timeout in seconds (adjust as needed)
69+
read_timeout = 2 # Reduced timeout (seconds)
7070
import time
7171

7272
start_time = time.time()
7373
while len(response_bytes) < max_read:
7474
try:
75-
# Read a small chunk to avoid blocking too long
7675
chunk = ssl_sock.read(128)
77-
if not chunk: # EOF or connection closed
76+
if not chunk:
7877
print('No more data received (EOF)')
7978
break
8079
print('Received chunk, length:', len(chunk), 'bytes:', chunk)
8180
response_bytes.extend(chunk)
8281
print('Total bytes received:', len(response_bytes))
82+
# Check for end of HTTP headers (\r\n\r\n)
83+
if b'\r\n\r\n' in response_bytes:
84+
print('End of HTTP headers detected')
85+
break
8386
except Exception as e:
8487
print('Error reading chunk:', e)
8588
break
@@ -91,40 +94,47 @@
9194
print('Raw response bytes:', response_bytes)
9295
print('Raw response hex:', response_bytes.hex())
9396

94-
# Attempt to decode response
97+
# Split HTTP response from any subsequent data
98+
http_end = response_bytes.find(b'\r\n\r\n') + 4
99+
if http_end < 4:
100+
ssl_sock.close()
101+
raise Exception('Invalid HTTP response: no headers found')
102+
http_response_bytes = response_bytes[:http_end]
103+
extra_bytes = response_bytes[http_end:] if http_end < len(response_bytes) else b''
104+
print('HTTP response bytes:', http_response_bytes)
105+
print('Extra bytes (if any):', extra_bytes)
106+
107+
# Decode HTTP response
95108
try:
96-
response = response_bytes.decode('utf-8')
97-
print('Decoded response:', response)
109+
response = http_response_bytes.decode('utf-8')
110+
print('Decoded HTTP response:', response)
98111
except UnicodeError as e:
99112
print('UnicodeError during decode:', e)
100-
# Try decoding with 'ignore' to see partial response
101-
response = response_bytes.decode('utf-8', errors='ignore')
102-
print('Decoded with errors ignored:', response)
103-
# Try alternative encoding (e.g., latin-1)
104-
try:
105-
response = response_bytes.decode('latin-1')
106-
print('Decoded as latin-1:', response)
107-
except Exception as e:
108-
print('Latin-1 decode failed:', e)
109-
# Dump printable characters
110-
printable = ''.join(c if 32 <= ord(c) < 127 else '.' for c in response_bytes.decode('latin-1'))
113+
# Dump printable characters as fallback
114+
printable = ''.join(c if 32 <= ord(c) < 127 else '.' for c in http_response_bytes.decode('latin-1'))
111115
print('Printable characters:', printable)
112116
ssl_sock.close()
113-
raise Exception('Failed to decode response')
117+
raise Exception('Failed to decode HTTP response')
114118

115119
# Check for valid WebSocket handshake
116120
if '101 Switching Protocols' not in response:
117121
print('Handshake response:', response)
118122
ssl_sock.close()
119123
raise Exception('Handshake failed')
120124

125+
# Push back extra bytes (WebSocket frame) to the socket
126+
if extra_bytes:
127+
print('Note: Extra bytes detected, will be handled by websocket module')
128+
121129
# Create WebSocket object
122130
ws = websocket(ssl_sock, True)
123131

124132
# Send and receive data
125133
ws.write('Hello, Secure WebSocket!')
126-
data = ws.read(1024)
127-
print('Received:', data)
134+
for _ in range(50):
135+
data = ws.read(1024)
136+
print('Received:', data)
137+
time.sleep_ms(100)
128138

129139
# Close connection
130140
ws.close()

0 commit comments

Comments
 (0)