-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpeer.py
More file actions
103 lines (91 loc) · 3.49 KB
/
peer.py
File metadata and controls
103 lines (91 loc) · 3.49 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
import socket
import os
import shutil
import time
FORMAT = "utf-8"
SIZE = 1024
ADDR = ("127.0.0.1", 4000)
def main():
print("Tune in to peer-to-peer!\nWhat's your port?")
IP = socket.gethostname()
PORT = int(input(">"))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Port saved!")
if not (os.path.exists("peers")):
os.mkdir("peers")
if not (os.path.exists("peers" + "/" + str(PORT))):
os.mkdir("peers" + "/" + str(PORT))
while True:
print("type \"help\" for help")
cmd = input(">>>>>")
match cmd:
case 'center':
client.connect(ADDR)
client.send(f"{PORT}".encode(FORMAT))
print(client.recv(SIZE).decode(FORMAT))
# after center
case 'listfiles':
list_files = os.listdir("peers" + "/" + str(PORT))
send_data = f"{cmd}@"
send_data += ",".join(list_files)
client.send(send_data.encode(FORMAT))
print(client.recv(SIZE).decode(FORMAT))
# after center
case 'listpeers':
client.send(cmd.encode(FORMAT))
print(client.recv(SIZE).decode(FORMAT))
# after center
case 'check':
print("Which file do you check:")
file_name = input()
send_data = f"{cmd}@{file_name}"
client.send(send_data.encode(FORMAT))
print(client.recv(SIZE).decode(FORMAT))
case 'help':
print("Available commands: quit, upl, downl, center")
case 'quit':
break
case 'upl':
client.bind((IP, PORT))
client.listen(PORT)
conn, addr = client.accept()
print("connected", addr)
filename = input("enter the file name: ")
conn.send(filename.encode(FORMAT))
with open("peers" + "/" + str(PORT) + "/" + filename, "rb") as f:
while True:
start = time.time()
bytes_read = f.read(SIZE)
if not bytes_read:
print("upload completed")
break
conn.sendall(bytes_read)
end = time.time()
if end - start > 0.2:
print("time out!")
break
conn.close()
case 'downl':
addresspeer = int(input("what is the peer's port :"))
client.bind((IP, PORT))
client.connect((IP, addresspeer))
filename = client.recv(SIZE).decode(FORMAT)
start = time.time()
with open("peers" + "/" + str(PORT) + "/" + filename, "wb") as f:
while True:
bytes_read = client.recv(SIZE)
if not bytes_read:
print("download completed")
break
f.write(bytes_read)
end = time.time()
if end - start > 0.2:
print("Time out!")
break
case _:
print("No command found with name", cmd)
#shutil.rmtree("peers/"+str(PORT))
client.close()
print("Disconnected")
if __name__ == "__main__":
main()