-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
67 lines (51 loc) · 1.64 KB
/
client.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
import socket
HEADER = 64
PORT = 12345
FORMAT = 'utf-8'
SERVER = '127.0.0.1'
ADDR = (SERVER,PORT)
DISCONNECT = 'DISCONNECT'
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def receive_file(client,file_name):
file_len = client.recv(HEADER).decode(FORMAT)
print('file len ',file_len,' ',int(file_len))
print(len(file_len))
if file_len:
file_data = client.recv(int(file_len)).decode(FORMAT)
print(file_data)
f = open(f'client\{file_name}','w')
f.write(file_data)
f.close()
def download_files_menu(PORT,SERVER):
# receiving files names
print('PORT No : ',PORT)
print('Server IP : ',SERVER)
change_values = input('\nChange default values ?? [ y/n ]')
if change_values =='y' or change_values =='Y':
PORT = input('PORT No : ')
SERVER = input('Server IP : ')
ADDR = (SERVER,PORT)
# connecting to server
client.connect(ADDR)
print(f'[CONNECTED] : connected to " {SERVER} ".')
msg = recv()
file_name = input(f'Choose a file to download:\n{msg}')
# sending file name for download
send(file_name)
receive_file(client,file_name)
send(DISCONNECT)
# for sending messages to server
def send(msg):
msg_len = str(len(msg))
msg_len += ' '* (HEADER - len(msg))
# sending message length
client.send(bytes(msg_len,FORMAT))
# sending real message
client.send(bytes(msg,FORMAT))
# for receiving messages from clients
def recv():
msg_len = client.recv(HEADER).decode(FORMAT)
if msg_len:
msg = client.recv(int(msg_len)).decode(FORMAT)
return msg
download_files_menu(PORT,SERVER)