-
Notifications
You must be signed in to change notification settings - Fork 17
/
server.py
83 lines (74 loc) · 2.35 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import argparse
import socket
from color_utils import *
class Server(object):
def __init__(self, host, port, protocol='tcp'):
self.clients = {}
self.order = []
self.files = []
self.online = False
self.protocol = protocol
self.sock = socket.socket()
try:
self.sock.bind((host, port))
self.host = host
self.port = port
self.online = True
except ConnectionRefusedError:
print("Connection refused...")
exit(1)
def listen(self, limit=5):
assert(self.online)
message = "..."
self.sock.listen(limit)
while True:
c = None
print("Listening...")
try:
c, addr = self.sock.accept()
gprint("Got connection from", addr)
message = self.ret_msg(c)
response = self.process(addr, message)
self.respond(c, response)
c.close()
except KeyboardInterrupt:
# The following may be useful, `ps -fA | grep python`
rprint("\nKeyboardInterrupt...\nSocket closed.")
if c:
c.close()
break
def process(self, addr, m):
self.clients[addr] = m
self.order.append(addr)
if m == 'PING':
return 'PONG'
elif m.split(' ')[0] == 'QUERY':
if m.split(' ')[1] in self.files:
return 'QUERYHIT'
else:
return 'NOT FOUND'
else:
return 'hello, World!'
def respond(self, sock, m):
assert(type(m) == str)
bprint("Sending message: ", m)
sock.send(m.encode())
def ret_msg(self, sock):
assert(self.online)
message = sock.recv(1024).decode('utf-8')
gprint("Received message: ", message)
return message
def close(self):
assert(self.online)
self.sock.close()
self.online = False
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, help="specify a port number \
(defaults to 12345)")
args = parser.parse_args()
p = args.port if args.port else 12345
# Feel free to change this
sock = Server(socket.gethostname(), p)
sock.listen()
sock.close()