-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
69 lines (56 loc) · 1.7 KB
/
Copy pathclient.py
File metadata and controls
69 lines (56 loc) · 1.7 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
"""Interactive CLI client for bytekv. Handles length-prefix framing."""
import socket
import struct
import sys
HOST = "localhost"
PORT = 9999
def send_framed(sock, message: bytes):
header = struct.pack("!I", len(message))
sock.sendall(header + message)
def recv_framed(sock) -> bytes:
header = recv_exact(sock, 4)
if not header:
return None
length = struct.unpack("!I", header)[0]
return recv_exact(sock, length)
def recv_exact(sock, n: int) -> bytes:
data = b""
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
return None
data += chunk
return data
def main():
# One-shot mode: python3 client.py SET foo bar
if len(sys.argv) > 1:
cmd = " ".join(sys.argv[1:])
with socket.socket() as s:
s.connect((HOST, PORT))
send_framed(s, cmd.encode())
resp = recv_framed(s)
if resp:
print(resp.decode(), end="")
return
# Interactive mode
print(f"bytekv client — connected to {HOST}:{PORT}")
print("Type commands (SET key val, GET key, ...). Ctrl-C to quit.\n")
with socket.socket() as s:
s.connect((HOST, PORT))
while True:
try:
cmd = input("bytekv> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not cmd:
continue
send_framed(s, cmd.encode())
resp = recv_framed(s)
if resp is None:
print("Server closed connection.")
break
print(resp.decode(), end="")
if __name__ == "__main__":
main()