forked from egemenyrlmz/peer2peer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
250 lines (204 loc) · 8.07 KB
/
client.py
File metadata and controls
250 lines (204 loc) · 8.07 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import tkinter as tk
from tkinter import messagebox, filedialog
import socket
import threading
import random
import os
SERVER_HOST = '54.234.0.174' # AWS sunucu adresi
SERVER_PORT = 5500 # AWS sunucu portu
# Bağlantı soketi için global değişkenler
client_socket = None
role = None # Kullanıcı rolü (SENDER veya RECEIVER)
username = None # Kullanıcı adı
receiver_list = [] # Güncel alıcı listesi
receiver_listbox = None # GUI'de alıcı listesi
def connect_to_server(username, selected_role):
"""
Sunucuya bağlanır ve kullanıcı rolüne göre bağlantı kurar.
"""
global client_socket, role
try:
# Soketi oluştur ve bağlan
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f"[*] Connected to server as {username} ({selected_role})")
# Kullanıcı rolünü belirle ve sunucuya mesaj gönder
client_socket.sendall(f"{selected_role}|{username}".encode('utf-8'))
role = selected_role
# Yeni sayfaya geç
open_dashboard(username, selected_role)
threading.Thread(target=listen_to_server, daemon=True).start()
except Exception as e:
messagebox.showerror("Connection Error", f"Failed to connect: {e}")
if client_socket:
client_socket.close()
client_socket = None
def listen_to_server():
"""
Sunucudan gelen mesajları dinler.
"""
global client_socket, receiver_list
try:
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
print(f"[Server]: {data}")
# Alıcı listesi güncelleme
if data.startswith("RECEIVER_LIST|"):
_, receivers = data.split("|", 1)
receiver_list = receivers.split(",") if receivers else []
update_receiver_list()
# Dosya alımı
elif data.startswith("FILE|"):
handle_incoming_file(data)
except Exception as e:
print(f"[!] Error while listening to server: {e}")
finally:
disconnect_from_server()
print("[*] Disconnected from server.")
def handle_incoming_file(file_header):
"""
Gelen dosya bilgilerini işler ve dosyayı alır.
"""
global client_socket
_, sender_name, filename, filesize = file_header.split("|")
filesize = int(filesize)
save_path = filedialog.asksaveasfilename(defaultextension=".txt",
initialfile=filename,
title="Save File As")
if not save_path:
messagebox.showerror("Error", "File save cancelled.")
return
file_data = b""
bytes_received = 0
try:
while bytes_received < filesize:
chunk = client_socket.recv(4096)
if not chunk:
break
file_data += chunk
bytes_received += len(chunk)
with open(save_path, 'wb') as f:
f.write(file_data)
messagebox.showinfo("Success", f"File '{filename}' saved to {save_path}.")
except Exception as e:
messagebox.showerror("Error", f"Failed to receive file: {e}")
def update_receiver_list():
"""
GUI'deki alıcı listesini günceller.
"""
if receiver_listbox:
receiver_listbox.delete(0, tk.END)
for receiver in receiver_list:
receiver_listbox.insert(tk.END, receiver)
def disconnect_from_server():
"""
Sunucu bağlantısını keser ve ana sayfaya döner.
"""
global client_socket
if client_socket:
try:
client_socket.close()
except Exception:
pass
client_socket = None
def send_file(filename, receiver):
"""
Seçilen dosyayı belirtilen kullanıcıya gönderir.
"""
global client_socket
if not client_socket:
messagebox.showerror("Error", "You are not connected to the server!")
return
if not filename or not receiver:
messagebox.showerror("Error", "Please select a file and a receiver!")
return
try:
filesize = os.path.getsize(filename)
header = f"SEND|{receiver}|{os.path.basename(filename)}|{filesize}"
client_socket.sendall(header.encode('utf-8'))
with open(filename, 'rb') as f:
while chunk := f.read(4096):
client_socket.sendall(chunk)
messagebox.showinfo("Success", f"File '{filename}' sent to {receiver}.")
except Exception as e:
messagebox.showerror("Error", f"Failed to send file: {e}")
def open_dashboard(username, role):
"""
Kullanıcı ana sayfasına geçiş yapar.
"""
dashboard = tk.Toplevel()
dashboard.title("Dashboard")
dashboard.configure(bg="white")
# Boyutları ayarla ve ekranın ortasında aç
dashboard.geometry("600x500")
dashboard.update_idletasks()
x = (dashboard.winfo_screenwidth() // 2) - (600 // 2)
y = (dashboard.winfo_screenheight() // 2) - (500 // 2)
dashboard.geometry(f"+{x}+{y}")
# Kullanıcı bilgisi
tk.Label(dashboard, text=f"{role}: {username}", font=("Arial", 16), bg="white", fg="blue").pack(pady=10)
# Receiver listesi ve dosya gönderme sadece SENDER için
if role == "SENDER":
tk.Label(dashboard, text="Receivers:", bg="white", fg="black").pack(pady=5)
global receiver_listbox
receiver_listbox = tk.Listbox(dashboard, height=15, width=40, bg="#f0f8ff", fg="black")
receiver_listbox.pack(pady=5)
# Dosya gönderme işlemi
def handle_send_file():
selected_receiver_idx = receiver_listbox.curselection()
if not selected_receiver_idx:
messagebox.showerror("Error", "Please select a receiver!")
return
selected_receiver = receiver_listbox.get(selected_receiver_idx)
filename = filedialog.askopenfilename()
if filename:
send_file(filename, selected_receiver)
tk.Button(dashboard, text="Send File", command=handle_send_file, bg="blue", fg="white", width=20).pack(pady=10)
# Çıkış butonu
tk.Button(dashboard, text="Exit", command=lambda: exit_to_main(dashboard), bg="red", fg="white", width=20).pack(pady=10)
def exit_to_main(dashboard):
"""
Çıkış işlemini gerçekleştirir ve ana ekrana döner.
"""
disconnect_from_server()
dashboard.destroy()
def start_gui():
"""
GUI'yi başlatır.
"""
def handle_connect():
global username
username = username_entry.get().strip()
if not username:
username = f"User{random.randint(1000, 9999)}"
selected_role = role_var.get()
if selected_role not in ["SENDER", "RECEIVER"]:
messagebox.showerror("Error", "Please select a role!")
return
connect_to_server(username, selected_role)
root = tk.Tk()
root.title("File Transfer Client")
root.configure(bg="white")
# Boyutları ayarla ve ekranın ortasında aç
root.geometry("600x500")
root.update_idletasks()
x = (root.winfo_screenwidth() // 2) - (600 // 2)
y = (root.winfo_screenheight() // 2) - (500 // 2)
root.geometry(f"+{x}+{y}")
# Başlık
tk.Label(root, text="File Transfer Client", font=("Arial", 18), bg="white", fg="blue").pack(pady=10)
# Kullanıcı adı
tk.Label(root, text="Enter Username:", bg="white", fg="black", font=("Arial", 12)).pack(pady=5)
username_entry = tk.Entry(root, font=("Arial", 12), width=30)
username_entry.pack(pady=5)
# Kullanıcı rolü
role_var = tk.StringVar(value="None")
tk.Radiobutton(root, text="Sender", variable=role_var, value="SENDER", bg="white", fg="black", font=("Arial", 12)).pack(pady=5)
tk.Radiobutton(root, text="Receiver", variable=role_var, value="RECEIVER", bg="white", fg="black", font=("Arial", 12)).pack(pady=5)
# Bağlan butonu
tk.Button(root, text="Connect to Server", command=handle_connect, bg="blue", fg="white", width=20, font=("Arial", 12)).pack(pady=10)
root.mainloop()
if __name__ == "__main__":
start_gui()