forked from vanbuile/NetworkApp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
237 lines (215 loc) · 8.86 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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import time
import socket
import os
import json
from threading import Thread
from messageProtocol import Message, Type, Header
import sys
SERVER_TIMEOUT = 5
CLPORT = 1111
class Server:
def __init__(self, server_port):
self.server_port = server_port
# Create dictionary for TCP table
self.clients = {}
self.hostname_file = {}
self.start()
def start(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((socket.gethostbyname(socket.gethostname()), self.server_port))
#
print(f"Server's running on {socket.gethostbyname(socket.gethostname())}, port: {self.server_port}")
self.server_socket.listen(5)
self.lis_t = Thread(target=self.listen, args=())
self.lis_t.start()
self.command()
def exit(self):
self.active = False
self.lis_t.join()
self.server_socket.close()
sys.exit(0)
def command(self):
while True:
request = input("Enter your request:")
if request == "ping":
print(f"Current clients:{self.clients}")
hostname = input("Chose hostname: ")
self.ping(hostname)
elif request == "discover":
print(f"Current_clients:{self.clients}")
hostname = input("Chose hostname: ")
self.discover(hostname)
elif request == "exit":
self.exit()
def listen(self):
self.active = True
while self.active:
try:
print("Running ... Waiting for connection")
client_socket, client_addr = self.server_socket.accept()
hostname = ""
for k, v in self.clients.items():
if client_addr[0] == v:
hostname = k
break
client_t = Thread(target=self.handle_client, args=(client_socket, hostname, client_addr[0]))
client_t.start()
except Exception as e:
raise Exception(e)
def register(self, client_socket:socket, message, ip):
hostname = message.get_info()['hostname']
payload = {'result': 'OK'}
for k in self.clients.keys():
if hostname == k:
payload['result'] = "DULICATED"
break
print(payload['result'])
if payload['result'] == 'OK':
self.clients[hostname] = ip
self.hostname_file[hostname] = []
print("Curent clients active: ", self.clients)
response = Message(Header.REGISTER, Type.RESPONSE, payload)
self.send(response, client_socket)
def handle_client(self, client_socket, hostname, ip):
print("Here")
try:
# Listen to message from client
client_socket.settimeout(SERVER_TIMEOUT)
message = client_socket.recv(2048).decode()
# Clients have terminated the connection
if not message:
client_socket.close()
# Clients have asked for request
else:
# Retrieve header and type
message = Message(None, None, None, message)
message_header = message.get_header()
# Handle each kind of message
# REQUEST, REGISTER
if message_header == Header.REGISTER:
self.register(client_socket, message, ip)
# REQUEST, PUBLISH
elif message_header == Header.PUBLISH:
self.publish(client_socket, hostname, message)
# REQUEST, FETCH
elif message_header == Header.FETCH:
self.fetch(client_socket, hostname, message)
# REQUEST, LEAVE
elif message_header == Header.LEAVE:
self.leave(client_socket, hostname)
except Exception as e:
print(f"Server request handling error for client {hostname}")
print(f"Status: {e}")
def publish(self, client_socket, hostname, message):
print("call pl")
info = message.get_info()
fname = info['fname']
lname = info['lname']
print(fname)
print(lname)
payload = { 'result': None}
if fname not in self.hostname_file[hostname]:
print("1")
self.hostname_file[hostname].append(fname)
payload['result'] = 'OK'
print("2")
else:
print("4")
payload['result'] = 'DUPLICATE'
print(payload)
response_message = Message(Header.PUBLISH, Type.RESPONSE, payload)
self.send(response_message, client_socket)
print("sent")
status = f"Client {hostname}: PUBLISH\n"
if payload['result'] == 'OK':
status += f'File name: {fname}\n'
status += f"Status: {payload['result']}\n"
return status
def ping(self, hostname):
if hostname not in list(self.clients.keys()):
return "PING: NOT FOUND THIS CLIENT\n"
ip = self.clients[hostname]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
try:
client_socket.settimeout(SERVER_TIMEOUT)
client_socket.connect((ip, CLPORT))
message = Message(Header.PING, Type.REQUEST, 'PING')
start_time = time.time()
self.send(message, client_socket)
response_message = client_socket.recv(2048).decode()
end_time = time.time()
response = Message(None, None, None, response_message)
RTT = "{:,.8f}".format(end_time - start_time)
if response_message:
print(f"PING OK: {response.get_info()['result']}")
print( f"Round-Trip Time: {RTT} (s)\n")
client_socket.close()
except Exception as e:
print(e)
def discover(self, hostname):
if hostname not in list(self.clients.keys()):
print("DISCOVER: NOT FOUND THIS CLIENT")
client_ip = self.clients[hostname]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
try:
client_socket.settimeout(SERVER_TIMEOUT)
client_socket.connect((client_ip, CLPORT))
message = Message(Header.DISCOVER, Type.REQUEST, 'DISCOVER')
start_time = time.time()
self.send(message, client_socket)
response_message = client_socket.recv(2048).decode()
end_time = time.time()
RTT = "{:,.8f}".format(end_time - start_time)
file_list = Message(None, None, None, response_message).get_info()["file_list"]
print(f"DISCOVER OK: {file_list}")
print(f"Round-Trip Time: {RTT} (s)\n")
except Exception as e:
print(e)
def fetch(self, client_socket, hostname, message):
fname = message.get_info()["fname"]
print(f"Got fname:{fname}")
ip_list = self.search(fname, hostname)
print(f"ip_list:{ip_list}")
payload = {'fname': fname, 'avail_ips': ip_list}
response = Message(Header.FETCH, Type.RESPONSE, payload)
self.send(response, client_socket)
status = f"Client {hostname}: FETCH\n"
status += f"File name: {fname}\n"
status += f"Status: OK\n"
return status
def search(self, fname, asking_hostname):
ip_list = []
print(f"clients: {list(self.clients.keys())}")
print(f"asking hostname{asking_hostname}")
print(f"hostname_file = {self.hostname_file}")
for hostname, file_list in self.hostname_file.items():
if asking_hostname != hostname and hostname in list(self.clients.keys()) and fname in file_list:
ip_list.append(self.clients[hostname])
return ip_list
def leave(self, client_socket, hostname):
self.clients.pop(hostname)
payload = {'result': 'OK'}
response = Message(Header.LEAVE, Type.RESPONSE, payload)
self.send(response, client_socket)
print(f"{hostname} LEAVE OK")
def send(self,msg: Message, sock: socket):
encoded_msg = json.dumps(msg.get_packet()).encode()
dest = sock.getpeername()[0]
try:
sock.sendall(encoded_msg)
print(f"Succesfull to send a {msg.get_header().name} message to {dest}" )
return True
except:
print(f"Failed to send a {msg.get_header().name} message to {dest}")
return False
SVPORT=8888
class ServerApp:
def __init__(self, server_port):
server = Server(server_port)
def main():
try:
app = ServerApp(SVPORT)
except Exception as e:
print(e)
if __name__ == "__main__":
main()