-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
96 lines (73 loc) · 3.41 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
from socket import *
import threading
import os , time
class Server:
def __init__(self, portNumber , isTracker = False):
self.__portNumber__ = portNumber
self.__listeningPortNumber__ = portNumber
self.listeningSocket = None
self.tempSocket = None
# each server can handle connections differently, so we assign the function based on the class
self.newConnectionsHandler = None
self.extraOperations = [] #each child might have 0 or more extra and different operations
self.isTracker = isTracker
self.UDP_socket = None
dir = f"Server_files"
if not os.path.exists(dir):
os.makedirs(f"./{dir}")
def startListening(self, host="127.0.0.1"):
self.listeningSocket = socket(AF_INET, SOCK_STREAM)
self.listeningSocket.bind((host, self.__portNumber__))
self.listeningSocket.listen(6)
def runServer(self):
self.startListening()
print(f"Server started. @ port: {self.__portNumber__}")
while True:
connection, addr = self.listeningSocket.accept()
print(f"Client connected IP < {addr} >")
listeningThread = threading.Thread(target=self.newConnectionsHandler, # this depends on what each of the inherited class will use
args=("listeningThread", connection)) # runs send file for each connection
listeningThread.start()
self.listeningSocket.close()
def start(self):
if len(self.extraOperations) > 1 : #we run the opertaitions each child has
for opertaion in self.extraOperations:
operationsThread = threading.Thread(target=opertaion)
operationsThread.start()
time.sleep(4)
runServerThread = threading.Thread(target=self.runServer)
runServerThread.start()
def sendFile(self, name, connection, filePath , typeOfReq = "EXISTS"):
# if Server.fileExists(filePath):
fileName = filePath.split("/")[-1]
connection.send(
f"{typeOfReq}|{os.path.getsize(f'{filePath}')}|{fileName}".encode())
userResponse = connection.recv(1024).decode()
if userResponse[:2] == "OK":
# we read the file as bytes
with open(f'./{filePath}', 'rb') as f:
bytesToSend = f.read(1024)
connection.send(bytesToSend)
while bytesToSend != b'': # since we cannot garuntee that the file size will be 1024 bytes, we keep sending until there is nothing
bytesToSend = f.read(1024)
connection.send(bytesToSend)
connection.close()
def establishTCPConnection(self , port , IPAddress = "127.0.0.1"):
try:
newSocket = socket(AF_INET, SOCK_STREAM)
newSocket.connect((IPAddress, port))
print(f"Connecting to {(IPAddress, port)}")
time.sleep(2)
return newSocket
except:
print(f"ERR: Cannot connect to <{IPAddress}, {port}>")
return None
@staticmethod
def fileExists(filePath) -> bool:
return os.path.isfile(filePath)
@property
def listeningPortNo(self):
return self.__listeningPort__
@property
def tempPocket(self):
return self.tempSocket