-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
64 lines (45 loc) · 1.23 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
59
60
61
62
63
64
#!/usr/bin/env python3.4
from socket import *
import _thread as thread
import time, pickle
MyHost = ''
MyPort = 9000
MyDict = {}
response = []
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((MyHost, MyPort))
sockobj.listen(5)
def now():
return time.ctime(time.time())
def commands(request):
for command in request:
if command[0] == 'add':
MyDict[command[1]] = command[2]
response.append(['added ', command[1], ' -> ', command[2]])
if command[0] == 'del':
del MyDict[command[1]]
response.append(['deleted ', command[1]])
if command[0] == 'read':
response.append(command[1], ' -> ', MyDict.get(command[1]))
if command[0] == 'list':
temp_dict = []
for i, j in MyDict.items():
response.append([i, ' -> ', j])
return response
def handleClient(connection):
while True:
data = connection.recv(1024)
if not data: break
commands(pickle.loads(data))
connection.send(pickle.dumps(response))
if len(response) > 0:
del response[:]
connection.close()
def dispatcher():
while True:
connection, address = sockobj.accept()
print('Server connected by', address, end=' ')
print('at', now())
thread.start_new_thread(handleClient, (connection,))
if __name__ == '__main__':
dispatcher()