-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservercode.py
More file actions
235 lines (208 loc) · 7.02 KB
/
servercode.py
File metadata and controls
235 lines (208 loc) · 7.02 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
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
import socket
import threading
import ntpath
import os
# HOST = "127.0.1.1"
HOST = socket.gethostbyname(socket.gethostname())
# print(HOST)
# print(socket.get hostname())
# Port to listen on (non-privileged ports are > 1023)
# integer from 1 to 65535
PORT = 65432
FORMAT = 'UTF-8'
def check_new_connection(sck: socket, addresses: [], sockets: []):
while True:
conn, addr = sck.accept()
addresses.append(addr)
sockets.append(conn)
print(f'new connection from {addr}')
def split_name(name: str):
number1 = name.find("<")
number2 = name.find(">", number1)
number3 = name.find("<", number2)
number4 = name.find(">", number3)
if number1 == -1 or number2 == -1 or number3 == -1 or number4 == -1:
result1 = ""
result2 = ""
else:
result1 = name[number1 + 1:number2]
result2 = name[number3 + 1:number4]
return [result1, result2]
def send_to_all(sockets: []):
i = 0
mess = input('command: ')
message = mess.encode(FORMAT)
msg = mess.split()
if msg[0].upper() == 'DOWNLOAD':
s1, s2 = split_name(mess)
for sock in sockets:
download_file(sock, s1, s2)
elif msg[0].upper() == 'UPLOAD':
s1, s2 = split_name(mess)
for sock in sockets:
upload_file(sock, s1, s2)
else:
for sock in sockets:
try:
sock.sendall(message)
except:
print(f'session {i} has interrupted')
data = sock.recv(1024).decode(FORMAT)
print('-------------------')
print(data)
i += 1
def download_file(socket_b: socket, file_address: str, destination: str):
add = ntpath.basename(file_address)
if not add:
print('file address invalid')
return False
filename = os.path.join(destination, add)
message = ('DOWNLOAD ' + file_address).encode(FORMAT)
try:
socket_b.sendall(message)
except:
print('the connection has interrupted')
return True
msg = "Successful".encode(FORMAT)
data = socket_b.recv(1024)
if data == "fILenOTopEn".encode(FORMAT):
print("file or path is invalid in client")
return False
try:
fp = open(filename, "wb")
socket_b.sendall(msg)
except IOError:
print('error! destination path invalid')
socket_b.sendall("NotSuccessful".encode(FORMAT))
return False
while data:
if data == "enDOfFiLe".encode(FORMAT):
break
else:
fp.write(data)
data = socket_b.recv(1024)
socket_b.sendall(msg)
print('Received successfully!')
fp.close()
return False
def upload_file(socket_b: socket, file_address: str, destination: str):
add = ntpath.basename(file_address)
if not add:
print('file address invalid')
return False
destination_address = destination + '/' + add
# filename = os.path.join(destination, add)
print(add)
message = ('UPLOAD ' + destination_address).encode(FORMAT)
try:
fp = open(file_address, "rb")
except IOError:
print('error! file_address invalid')
return False
try:
socket_b.sendall(message)
except:
print('the connection has interrupted')
return True
msg = socket_b.recv(1024).decode(FORMAT)
if msg != 'Successful':
fp.close()
print('a problem occurred or path does not exist in client')
return False
data = fp.read(1024)
while data:
try:
socket_b.sendall(data)
msg = socket_b.recv(1024).decode(FORMAT)
if msg != 'Successful':
fp.close()
print('a problem occurred')
return False
except:
print('the connection has interrupted')
return True
data = fp.read(1024)
data = "enDOfFiLe".encode(FORMAT)
socket_b.sendall(data)
msg = socket_b.recv(1024).decode(FORMAT)
if msg != 'Successful':
print('a problem occurred')
fp.close()
return False
def session_command(socket_a: socket, address, number: int):
flag = False
while True:
msg = input(f'session {number}: ')
msg_split = msg.split()
if msg_split[0] == 'back':
break
elif msg_split[0].upper() == 'DOWNLOAD':
s1, s2 = split_name(msg)
flag = download_file(socket_a, s1, s2)
continue
elif msg_split[0].upper() == 'UPLOAD':
s1, s2 = split_name(msg)
flag = upload_file(socket_a, s1, s2)
continue
elif msg == 'close connection':
socket_a.close()
return True
else:
message = msg.encode('UTF-8')
try:
socket_a.sendall(message)
except:
print('the connection has interrupted')
flag = True
break
data = socket_a.recv(1024).decode(FORMAT)
if not data:
print('the connection has interrupted')
flag = True
break
print(data)
return flag
def print_list_connections(addresses: []):
print(f'number of sessions: {addresses.__len__()}')
i = 0
for address in addresses:
print(f'session {i}: {address}')
i += 1
# print('guide: ')
# print('change name --------> change session name')
# print('sort ---------------> sort sessions based on names')
# print('close connection ---> gets session number and closes client connection')
# print('back ---------------> back to session controller')
# inp = input()
# if inp == 'back':
# return
address_arr = []
socket_arr = []
print("[STARTING] server is starting...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print(f'[LISTENING] Server is listening on {HOST}...')
thread = threading.Thread(target=check_new_connection, args=(s, address_arr, socket_arr))
thread.start()
while True:
session = input('session controller: ')
s = session.split()
if s[0] == 'session':
session_num = int(s[1])
if 0 <= session_num < address_arr.__len__():
check = session_command(socket_arr[session_num], address_arr[session_num], session_num)
if check:
socket_arr.pop(session_num)
address_arr.pop(session_num)
elif s[0] == 'close':
exit(100)
break
elif session == 'list of sessions':
print_list_connections(address_arr)
elif session == 'send to all':
send_to_all(socket_arr)
elif s[0] == 'help':
print('list of sessions ----> print all sessions')
print('session (number) ----> opens a session to send commands')
print('send to all ---------> send one command to all sessions')