MCPcopy Create free account
hub / github.com/NVIDIA/OpenShell / websocket_client_script

Function websocket_client_script

e2e/rust/tests/websocket_conformance.rs:308–425  ·  view source on GitHub ↗
(host: &str, port: u16)

Source from the content-addressed store, hash-verified

306}
307
308fn websocket_client_script(host: &str, port: u16) -> String {
309 format!(
310 r#"
311import base64
312import json
313import os
314import socket
315import struct
316import time
317import urllib.parse
318
319HOST = {host:?}
320PORT = {port}
321TOKEN_ENV = {token_env:?}
322
323def recv_until(sock, marker):
324 data = b""
325 while marker not in data:
326 chunk = sock.recv(4096)
327 if not chunk:
328 break
329 data += chunk
330 return data
331
332def read_exact(sock, size):
333 data = b""
334 while len(data) < size:
335 chunk = sock.recv(size - len(data))
336 if not chunk:
337 raise EOFError("unexpected end of websocket frame")
338 data += chunk
339 return data
340
341def masked_text_frame(payload):
342 data = payload.encode("utf-8")
343 mask = os.urandom(4)
344 if len(data) < 126:
345 header = bytes([0x81, 0x80 | len(data)])
346 elif len(data) <= 0xFFFF:
347 header = bytes([0x81, 0x80 | 126]) + struct.pack("!H", len(data))
348 else:
349 header = bytes([0x81, 0x80 | 127]) + struct.pack("!Q", len(data))
350 masked = bytes(byte ^ mask[index % 4] for index, byte in enumerate(data))
351 return header + mask + masked
352
353def read_frame(sock):
354 first, second = read_exact(sock, 2)
355 length = second & 0x7F
356 if length == 126:
357 length = struct.unpack("!H", read_exact(sock, 2))[0]
358 elif length == 127:
359 length = struct.unpack("!Q", read_exact(sock, 8))[0]
360 mask = read_exact(sock, 4) if second & 0x80 else b""
361 payload = read_exact(sock, length)
362 if mask:
363 payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
364 return first, payload
365

Calls

no outgoing calls

Tested by

no test coverage detected