-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.py
More file actions
33 lines (25 loc) · 757 Bytes
/
protocol.py
File metadata and controls
33 lines (25 loc) · 757 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import json
BUFFER_SIZE = 4096
def send_json(sock, data):
try:
message = json.dumps(data) + "\n"
sock.sendall(message.encode())
except Exception as e:
print("Send error:", e)
def recv_json(sock, buffer):
try:
chunk = sock.recv(BUFFER_SIZE).decode()
if not chunk:
return [], buffer
buffer += chunk
messages = []
while "\n" in buffer:
message, buffer = buffer.split("\n", 1)
try:
messages.append(json.loads(message))
except json.JSONDecodeError:
print("Invalid JSON skipped")
return messages, buffer
except Exception as e:
print("Receive error:", e)
return [], buffer