當然可以!根據之前的建議,我將針對你的程式碼進行一些修正和優化。以下是修改後的程式碼片段:
python
複製程式碼
import socket
import threading
import tkinter as tk
from tkinter import filedialog, ttk, messagebox, simpledialog
import time
import os
import subprocess
from tkinter.scrolledtext import ScrolledText
import psutil # 用於獲取網路介面資訊
class Server:
def __init__(self, root):
self.root = root
self.root.title("Server UDP傳送檔案")
self.root.geometry("800x600")
self.network_interfaces = self.get_network_interfaces()
if not self.network_interfaces:
messagebox.showerror("錯誤", "未找到有效的網路介面!")
self.root.quit()
return
self.selected_interface = tk.StringVar(value=list(self.network_interfaces.keys())[0])
# 標題與 IP 顯示
header_frame = tk.Frame(self.root)
header_frame.pack(pady=10)
self.title_label = tk.Label(header_frame, text="UDP派送檔案", font=("Arial", 18), fg="deepskyblue")
self.title_label.pack(side=tk.LEFT, pady=10)
self.server_ip = self.get_local_ip()
self.ip_label = tk.Label(header_frame, text=f"伺服器端 IP: {self.server_ip}", font=("Arial", 14))
self.ip_label.pack(side=tk.LEFT, padx=(10, 0))
# 網路卡選擇下拉選單
self.interface_label = tk.Label(self.root, text="選擇網路卡:")
self.interface_label.pack(pady=5)
self.interface_dropdown = ttk.Combobox(self.root, textvariable=self.selected_interface, values=list(self.network_interfaces.keys()))
self.interface_dropdown.pack(pady=5)
self.interface_dropdown.bind("<<ComboboxSelected>>", self.update_ip_display)
# 建立表格
self.tree = ttk.Treeview(root, columns=("IP", "MAC", "Name", "Status"), show='headings')
for col in ("IP", "MAC", "Name", "Status"):
self.tree.heading(col, text=col, anchor="center")
self.tree.column(col, anchor="center")
self.tree.pack(fill=tk.BOTH, expand=True)
self.client_data_dict = {}
# 按鈕區域
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10)
self.broadcast_button = tk.Button(button_frame, text="手動廣播伺服器", command=self.start_broadcast_manually)
self.broadcast_button.pack(side=tk.LEFT, padx=(0, 10))
self.transfer_button = tk.Button(button_frame, text="傳送檔案", command=self.select_client_and_file)
self.transfer_button.pack(side=tk.LEFT, padx=(0, 10))
self.send_text_button = tk.Button(button_frame, text="傳送文字", command=self.send_text)
self.send_text_button.pack(side=tk.LEFT, padx=(0, 10))
self.select_all_button = tk.Button(button_frame, text="全選 client 端", command=self.select_all_clients, fg="navy")
self.select_all_button.pack(side=tk.LEFT, padx=5, pady=10)
self.deselect_all_button = tk.Button(button_frame, text="取消全選 client 端", command=self.deselect_all_clients, fg="purple")
self.deselect_all_button.pack(side=tk.LEFT, padx=5, pady=10)
# 訊息區域
self.output_area = ScrolledText(self.root, height=10)
self.output_area.pack(fill=tk.BOTH, pady=10)
# 啟動伺服器
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.server_socket.bind(("", 37020))
threading.Thread(target=self.receive_clients, daemon=True).start()
threading.Thread(target=self.broadcast_for_30_seconds, daemon=True).start()
def get_network_interfaces(self):
interfaces = {}
for interface, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == socket.AF_INET:
interfaces[interface] = addr.address
return interfaces
def get_local_ip(self):
selected_interface = self.selected_interface.get()
return self.network_interfaces[selected_interface]
def update_ip_display(self, event):
self.server_ip = self.get_local_ip()
self.ip_label.config(text=f"伺服器端 IP: {self.server_ip}")
def set_buttons_state(self, state):
for button in [self.broadcast_button, self.transfer_button, self.select_all_button, self.deselect_all_button]:
button.config(state=tk.DISABLED if not state else tk.NORMAL)
def select_all_clients(self):
self.tree.selection_set(self.tree.get_children())
def deselect_all_clients(self):
self.tree.selection_remove(self.tree.get_children())
def receive_clients(self):
while True:
try:
data, addr = self.server_socket.recvfrom(1024)
client_data = data.decode().split(',')
if len(client_data) == 3:
client_ip, client_mac, client_name = client_data
if client_ip != self.server_ip:
self.update_or_insert_client(client_ip, client_mac, client_name, "Online")
else:
self.update_output(f"接收到不完整的資料:{client_data}\n")
except Exception as e:
self.update_output(f"接收資料時發生錯誤: {e}\n")
def update_or_insert_client(self, ip, mac, name, status):
if ip in self.client_data_dict or mac in self.client_data_dict:
item_id = self.client_data_dict.get(ip) or self.client_data_dict.get(mac)
self.tree.item(item_id, values=(ip, mac, name, status))
else:
item_id = self.tree.insert("", "end", values=(ip, mac, name, status))
self.client_data_dict[ip] = item_id
self.client_data_dict[mac] = item_id
def broadcast_for_30_seconds(self):
start_time = time.time()
while time.time() - start_time < 30:
try:
self.server_socket.sendto(b"Server here", ('<broadcast>', 37020))
time.sleep(5)
except Exception as e:
self.update_output(f"廣播時發生錯誤: {e}\n")
self.update_output("廣播已停止\n")
def start_broadcast_manually(self):
threading.Thread(target=self.broadcast_for_30_seconds, daemon=True).start()
def send_text(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "請至少選擇一個 client 端")
return
text_input = simpledialog.askstring("輸入文字", "請輸入要傳送的文字:")
if text_input:
client_ips = [self.tree.item(item, 'values')[0] for item in selected_items]
for client_ip in client_ips:
self.send_text_to_clients(client_ip, text_input)
def send_text_to_clients(self, client_ip, text):
try:
self.server_socket.sendto(text.encode(), (client_ip, 8520))
self.update_output(f"文字已傳送至 {client_ip}: {text}\n")
except Exception as e:
self.update_output(f"傳送文字時發生錯誤: {e}\n")
def select_client_and_file(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "請至少選擇一個 client 端")
return
client_ips = [self.tree.item(item, 'values')[0] for item in selected_items]
file_paths = filedialog.askopenfilenames(title="選擇檔案")
if file_paths:
for client_ip in client_ips:
self.prepare_file_transfer_list(client_ip, file_paths)
def prepare_file_transfer_list(self, client_ip, file_paths):
transfer_list = "\n".join(file_paths)
self.update_output(f"準備傳輸檔案到 {client_ip}:\n{transfer_list}\n")
threading.Thread(target=self.send_file_list, args=(client_ip, file_paths), daemon=True).start()
def send_file_list(self, client_ip, file_paths):
try:
file_list_str = ",".join(file_paths)
self.server_socket.sendto(file_list_str.encode(), (client_ip, 8500))
self.update_output(f"檔案傳輸清單已傳送至 {client_ip}\n")
time.sleep(2)
selected_clients = self.tree.selection()
client_count = len(selected_clients)
for file_path in file_paths:
if os.path.exists(file_path):
self.run_udp_sender(client_ip, file_path, client_count)
except Exception as e:
self.update_output(f"傳送檔案清單時發生錯誤: {e}\n")
def run_udp_sender(self, client_ip, file_path, client_count):
self.set_buttons_state(False)
if os.path.exists(file_path):
command = [
'udp-sender.exe',
'--file', file_path,
'--port', '8500',
'--min-receivers', str(client_count),
'--autostart', '5'
]
threading.Thread(target=self.execute_command, args=(command,), daemon=True).start()
def execute_command(self, command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for stdout_line in process.stdout:
self.update_output(stdout_line)
for stderr_line in process.stderr:
self.update_output(stderr_line)
process.stdout.close()
process.stderr.close()
process.wait()
self.set_buttons_state(True)
def update_output(self, message):
def append_message(msg):
self.output_area.insert(tk.END, msg)
self.output_area.see(tk.END)
self.root.after(0, lambda: append_message(message))
# 啟動伺服端
root = tk.Tk()
server = Server(root)
root.mainloop()
網路介面檢查:新增檢查是否找到有效的網路介面,若無則顯示錯誤訊息並退出。
錯誤處理:改善了錯誤處理機制,能更清楚地提示用戶。
按鈕狀態管理:確保在傳送檔案時能正確鎖定和解鎖按鈕。
簡化重複代碼:將重複的按鈕列表管理封裝進 set_buttons_state 方法。
文字傳送:在傳送文字時,檢查選擇的客戶端清單是否為空。
這些修改旨在提高程式的穩定性和可讀性。希望這能幫助你進一步完善程式!如果有任何疑問或需要進一步的改進,隨時告訴我!