BOSS commited on
Commit
e0c473b
·
1 Parent(s): f3d9771

增加回显1

Browse files
Files changed (1) hide show
  1. app.py +17 -8
app.py CHANGED
@@ -45,24 +45,33 @@ async def websocket_endpoint(websocket: WebSocket):
45
  # binary frame handling
46
  if "bytes" in msg:
47
  data = msg.get("bytes") or b""
48
- # Expecting length-prefixed: 4-byte BE length + payload
49
- if len(data) < 4:
50
- # ignore or notify client
 
 
 
 
 
 
 
 
 
 
51
  await websocket.send_text("error: frame too short")
52
  continue
53
- length = int.from_bytes(data[:4], "big")
54
- payload = data[4:4+length]
55
 
56
  # Log frame summary (length and first up to 32 bytes as hex)
57
  try:
58
  sample = payload[:32]
59
  sample_hex = sample.hex()
60
- print(f"Received binary frame length={length} sample={sample_hex}")
61
  except Exception:
62
  print(f"Received binary frame length={length} (sample unavailable)")
63
 
64
- # For demo, echo payload back in same frame format
65
- resp = len(payload).to_bytes(4, "big") + payload
 
66
  try:
67
  await websocket.send_bytes(resp)
68
  except Exception:
 
45
  # binary frame handling
46
  if "bytes" in msg:
47
  data = msg.get("bytes") or b""
48
+ # Support two possible binary formats:
49
+ # New multiplex format: 1-byte type + 4-byte BE length + payload
50
+ # Legacy format: 4-byte BE length + payload
51
+ if len(data) >= 5 and data[0:1] in (b'D', b'O'):
52
+ frame_type = data[0:1]
53
+ length = int.from_bytes(data[1:5], "big")
54
+ payload = data[5:5+length]
55
+ elif len(data) >= 4:
56
+ # legacy
57
+ frame_type = b'D'
58
+ length = int.from_bytes(data[:4], "big")
59
+ payload = data[4:4+length]
60
+ else:
61
  await websocket.send_text("error: frame too short")
62
  continue
 
 
63
 
64
  # Log frame summary (length and first up to 32 bytes as hex)
65
  try:
66
  sample = payload[:32]
67
  sample_hex = sample.hex()
68
+ print(f"Received binary frame type={frame_type.decode(errors='ignore')} length={length} sample={sample_hex}")
69
  except Exception:
70
  print(f"Received binary frame length={length} (sample unavailable)")
71
 
72
+ # For demo, echo payload back in same frame format (preserve frame_type)
73
+ resp_header = frame_type + len(payload).to_bytes(4, "big")
74
+ resp = resp_header + payload
75
  try:
76
  await websocket.send_bytes(resp)
77
  except Exception: