-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
58 lines (46 loc) · 1.78 KB
/
server.py
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
import socket
import threading
from src.resp import serialize_resp, deserialize_resp
from src.commands import handle_ping, handle_set, handle_get, handle_echo, handle_default
HOST = '127.0.0.1'
PORT = 6380
data_store = {}
def handle_client(client_socket, data_store):
command_handlers = {
'ping': handle_ping,
'set': lambda message: handle_set(message, data_store),
'get': lambda message: handle_get(message, data_store),
'echo': handle_echo,
}
while True:
resp_message = client_socket.recv(4096)
if not resp_message:
break
message, _ = deserialize_resp(resp_message)
if not isinstance(message, list):
response = "ERROR: Command must be an array with at least 2 elements"
else:
command = message[0].lower()
handler = command_handlers.get(command, handle_default)
response = handler(message)
client_socket.send(serialize_resp(response))
def start_client_thread(client_socket):
client_thread = threading.Thread(target=handle_client, args=(client_socket, data_store))
client_thread.start()
def redis_lite_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Redis Lite server listening on {HOST}:{PORT}")
try:
while True:
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}")
start_client_thread(client_socket)
except KeyboardInterrupt:
print("Shutting down server...")
finally:
server_socket.close()
if __name__ == "__main__":
redis_lite_server()