-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeyValueServer.py
More file actions
152 lines (117 loc) · 3.2 KB
/
keyValueServer.py
File metadata and controls
152 lines (117 loc) · 3.2 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import socket
import json
from _thread import *
import threading
import time
import os
import random
IFACE = "0.0.0.0"
PORT = "9889"
INITIAL_BUFFER_SIZE = 1024
DATA_FILE = "keyValue.json"
END_STRING = "\r\n"
global kvData
kvData = {}
commands = {
'SET' : "set",
'GET' : "get",
'DELETE' : "delete"
}
response = {
"stored" : "STORED",
"notStored" : "NOT-STORED",
"end" : "END"
}
def recieveData(sock):
data = b''
while(1):
chunk = sock.recv(INITIAL_BUFFER_SIZE)
data = data+ chunk
if len(chunk) < INITIAL_BUFFER_SIZE:
break
return data.decode('utf-8')
def getValue(key):
result = []
if key in kvData:
result = kvData[key]
return result
def setValue(key, value, flag, length):
threadLockHandle.acquire()
try:
value = value
with open(DATA_FILE, 'w', encoding='utf-8') as filename:
kvData[key] = [value, flag, length]
json.dump(kvData, filename)
filename.close()
except error:
print('Exception: ', error)
finally:
threadLockHandle.release()
def deleteFile():
global kvData
try:
with open(DATA_FILE, 'w') as filename:
kvData = {}
filename.close()
except error:
print('Exception: ', error)
def handleClient(connection, isSleep):
try:
responseMessage = ""
dataBytes = recieveData(connection).split("\r\n")
keyString = dataBytes[0].split(" ")
valueString = "".join(dataBytes[1:])
action = keyString[0]
key = keyString[1]
if isSleep:
time.sleep(random.random())
if action == commands['SET']:
setValue(key, valueString, keyString[2], keyString[4])
responseMessage = response["stored"] + END_STRING
elif action == commands['GET']:
val = getValue(key)
if val and val[0]:
res = val[0]
firstMessage = f"VALUE {key} {val[1]} {val[2]}{END_STRING}"
secondMessage = f"{res}{END_STRING}"
sendResponse(firstMessage, connection)
sendResponse(secondMessage, connection)
responseMessage = response["end"] + END_STRING
elif action == commands['DELETE']:
deleteFile()
responseMessage = response["stored"] + END_STRING
pass
else:
raise Exception('Invalid command')
sendResponse(responseMessage, connection)
except error:
print("Exception Occured : ", error)
pass
def sendResponse(response, connection):
try:
connection.sendall(response.encode())
except error:
print('Exception:', error)
pass
if __name__ == "__main__":
global threadLockHandle
print("Hello, I am a server")
threadLockHandle = threading.Lock()
addrInfo = socket.getaddrinfo(IFACE, PORT)
socketType = socket.SOCK_STREAM
with open(DATA_FILE, 'w+') as filename:
if not os.stat(DATA_FILE).st_size:
json.dump({}, filename)
kvData = {}
else:
kvData = json.load(filename)
filename.close()
#Initialising socket
connectionSocket = socket.socket(socket.AF_INET, socketType)
connectionSocket.bind((addrInfo[0][-1][0], addrInfo[0][-1][1]))
connectionSocket.listen()
while(1):
connection, address = connectionSocket.accept()
print(f"connection from {address}")
newThread = threading.Thread(target=handleClient, args=(connection, False))
newThread.start()