除錯用
查看所有使用中的端口
netstat -aon
如果只想查看 8080 端口的使用情況,可以輸入:
netstat -aon | findstr :8080
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 1234(PID)
查詢進程名稱:
tasklist | findstr 5678
終止進程:使用以下命令終止該進程:
taskkill /PID <進程ID> /F
taskkill /PID 1234 /F
功能-alert一個文字訊息框
from tkinter import messagebox
# 完成傳輸,更新狀態
self.status_label.config(text="目前傳輸狀態:傳輸完成!")
messagebox.showinfo("傳輸完成", "檔案已完成傳輸!")→使用者看到
功能-
# 設定固定路徑或動態取得Python執行檔所在目錄的路徑
use_system32_path = True # 設定True則使用C:\Windows\System32,False則使用與Python執行檔相同目錄
if use_system32_path:
udp_sender_path = "C:/Windows/System32/udp-sender.exe"
else:
script_dir = os.path.dirname(sys.executable)
udp_sender_path = os.path.join(script_dir, "udp-sender.exe")
功能
-要讓 udp-receiver.exe 以背景方式執行且不顯示終端機畫面,可以使用 subprocess.CREATE_NO_WINDOW 選項。這個選項會讓程序在沒有控制台窗口的情況下運行。以下是一個修改後的範例:
import subprocess
process = subprocess.Popen(
['udp-receiver.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
這樣,udp-receiver.exe 就會在背景執行,且不會顯示任何終端機窗口。如果你需要從這個背景進程中讀取輸出,你可以使用 process.stdout.read() 或者 process.stdout.readline() 來捕獲輸出。例如:
import subprocess
process = subprocess.Popen(
['udp-receiver.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
# 讀取輸出
output, _ = process.communicate()
print(output)
這樣,你可以在不顯示終端機窗口的情況下,背景執行程序並捕獲其輸出。
1130925-原型
pip install PyQt5
這樣,udp-sender.exe 就會在背景執行,且不會顯示任何終端機窗口。如果你需要從這個背景進程中讀取輸出,你可以使用 process.stdout.read() 或者 process.stdout.readline() 來捕獲輸出。例如:
import subprocess
process = subprocess.Popen(
['udp-sender.exe', '--file', save_path, '--port', '8500'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
# 讀取輸出
output, _ = process.communicate()
print(output)
這樣,你可以在不顯示終端機窗口的情況下,背景執行程序並捕獲其輸出。
-檔案傳輸機制: 使用subprocess來啟動udp-sender.exe和udp-receiver.exe。
python
複製程式碼
import subprocess
def send_file(file_path, client_ip):
udp_sender_command = f"udp-sender.exe --file {file_path} --port 8500 --min-receivers 1 --interface 伺服端的網路介面"
subprocess.run(udp_sender_command, shell=True)
def receive_file(destination_folder):
udp_receiver_command = f"udp-receiver.exe --file {destination_folder} --port 9000"
subprocess.run(udp_receiver_command, shell=True)
# 使用 udp-receiver.exe 接收檔案
for file_name in file_list:
save_path = os.path.join("received_files", os.path.basename(file_name))
subprocess.run(['udp-receiver.exe', '--file', save_path, '--port', '8500'])
你可以在https://www.udpcast.linux.lu/exe.html上下載udp-sender.exe和udp-receiver.exe,並配置正確的指令來執行檔案傳輸。
伺服端的廣播與接收: 使用Python的socket模組進行UDP廣播。
python
複製程式碼
import socket
import threading
import time
BROADCAST_INTERVAL = 30 # 秒
BROADCAST_PORT = 37020
BROADCAST_MESSAGE = "伺服端IP地址: {}"
def broadcast_ip(ip_address):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
end_time = time.time() + BROADCAST_INTERVAL
while time.time() < end_time:
message = BROADCAST_MESSAGE.format(ip_address).encode()
sock.sendto(message, ('<broadcast>', BROADCAST_PORT))
time.sleep(5) # 每5秒廣播一次
sock.close()
def start_broadcast(ip_address):
threading.Thread(target=broadcast_ip, args=(ip_address,)).start()
Client端的報到機制: Client端接收伺服端的廣播,並回報其資訊。
python
複製程式碼
import socket
def report_to_server(server_ip, client_info):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
report_message = f"{client_info['ip']},{client_info['mac']},{client_info['name']},online"
sock.sendto(report_message.encode(), (server_ip, BROADCAST_PORT))
sock.close()
def listen_for_broadcast():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', BROADCAST_PORT))
while True:
data, addr = sock.recvfrom(1024)
server_ip = addr[0]
client_info = {
'ip': socket.gethostbyname(socket.gethostname()),
'mac': get_mac_address(), # 假設有一個取得MAC地址的函數
'name': socket.gethostname(),
}
report_to_server(server_ip, client_info)
UI展示與互動(伺服端): 可以使用tkinter來簡單實作一個圖形界面,來顯示Client端的報到狀態,並允許伺服端使用者手動重新廣播。
python
複製程式碼
import tkinter as tk
class ServerUI:
def __init__(self, root):
self.root = root
self.root.title("檔案傳輸伺服端")
self.clients_list = tk.Listbox(root, width=50, height=10)
self.clients_list.pack()
self.broadcast_button = tk.Button(root, text="手動廣播", command=self.manual_broadcast)
self.broadcast_button.pack()
def update_clients(self, client_info):
# 假設client_info包含ip, mac, name, status
self.clients_list.insert(tk.END, f"{client_info['ip']} - {client_info['mac']} - {client_info['name']} - {client_info['status']}")
def manual_broadcast(self):
# 重新廣播伺服端IP
start_broadcast("伺服端的IP地址")
root = tk.Tk()
server_ui = ServerUI(root)
root.mainloop()
檔案傳輸機制: 使用subprocess來啟動udp-sender.exe和udp-receiver.exe。
python
複製程式碼
import subprocess
def send_file(file_path, client_ip):
udp_sender_command = f"udp-sender.exe --file {file_path} --port 9000 --min-receivers 1 --interface 伺服端的網路介面"
subprocess.run(udp_sender_command, shell=True)
def receive_file(destination_folder):
udp_receiver_command = f"udp-receiver.exe --file {destination_folder} --port 9000"
subprocess.run(udp_receiver_command, shell=True)
你可以在https://www.udpcast.linux.lu/exe.html上下載udp-sender.exe和udp-receiver.exe,並配置正確的指令來執行檔案傳輸。
客戶端與伺服端的互動是通過UDP進行的,為了增強穩定性,可以增加確認機制,例如回報成功或失敗的傳輸狀態。
希望這個方案能幫助你開始實作檔案傳輸功能。如果有其他問題或需要進一步的調整,隨時告訴我!
1130926-原型
import os
import tkinter as tk
from tkinter import filedialog
import subprocess
import sys
# 設定固定路徑或動態取得Python執行檔所在目錄的路徑
use_system32_path = True # 設定True則使用C:\Windows\System32,False則使用與Python執行檔相同目錄
if use_system32_path:
udp_sender_path = "C:/Windows/System32/udp-sender.exe"
else:
script_dir = os.path.dirname(sys.executable)
udp_sender_path = os.path.join(script_dir, "udp-sender.exe")
# 建立主窗口
root = tk.Tk()
root.title("UDP 檔案傳輸工具")
# 設定窗口大小
root.geometry("400x250")
# 選擇檔案的函數
def select_file():
file_path = filedialog.askopenfilename(title="選擇要傳送的檔案")
if file_path:
display_file_info(file_path)
start_udp_sender(file_path)
# 顯示檔案名稱和大小的函數
def display_file_info(file_path):
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
file_info_label.config(text=f"檔案名稱: {file_name}\n檔案大小: {file_size} bytes")
# 呼叫udp-sender.exe進行檔案傳輸
def start_udp_sender(file_path):
command = [udp_sender_path, "--file", file_path, "--port", "8600"]
try:
# 在執行命令前打印出命令內容以供檢查
print(f"執行命令: {' '.join(command)}")
subprocess.run(command, check=True)
result_label.config(text="檔案傳輸已開始", fg="green")
except subprocess.CalledProcessError as e:
# 捕捉詳細的錯誤訊息
result_label.config(text=f"檔案傳輸失敗: {str(e)}", fg="red")
print(f"錯誤詳情: {e.output}")
# 建立按鈕與標籤
select_button = tk.Button(root, text="選擇派送檔案", command=select_file)
select_button.pack(pady=10)
# 顯示傳輸狀態的標籤
result_label = tk.Label(root, text="", fg="blue")
result_label.pack(pady=10)
# 建立檔案名稱與檔案大小顯示區域
file_info_label = tk.Label(root, text="檔案名稱: \n檔案大小: ", fg="black")
file_info_label.pack(pady=10)
# 標題"UDP檔案派送工具"
title_label = tk.Label(root, text="UDP檔案派送工具", font=("Arial", 18), fg="blue")
title_label.pack(pady=20)
# 啟動主循環
root.mainloop()
1130930
用繁體中文,在w11下,跟據"http://www.udpcast.linux.lu/cmd.html"、"http://www.udpcast.linux.lu/exe.html",如果發送端要一次傳2個檔案,並在且接收端連接後,自動啟動傳輸,在發送端跟接收別分別要用什麼指令?能給我完整的範例嗎?
"C:\Windows\System32\udp-receiver.exe"
"C:\Windows\System32\udp-sender.exe"
# 設定固定路徑或動態取得Python執行檔所在目錄的路徑
use_system32_path = True # 設定True則使用C:\Windows\System32,False則使用與Python執行檔相同目錄
if use_system32_path:
udp_sender_path = "C:/Windows/System32/udp-sender.exe"
else:
script_dir = os.path.dirname(sys.executable)
udp_sender_path = os.path.join(script_dir, "udp-sender.exe")
udp-sender --file C:\path\to\file1.txt --file C:\path\to\file2.txt --destination 192.168.1.100 --port 5000 --bandwidth 1m
發送端使用:
udp-sender --file <檔案路徑> --dest <接收端IP>:9000
發送單個檔案 :
udp-sender --file C:\path\to\your\file.txt --dest 192.168.1.2:9000
發送整個目錄中的所有檔案 :
使用 --file 選項指定目錄:
udp-sender --file C:\path\to\your\directory\* --dest 192.168.1.2:9000
指定傳輸速度 :
可以使用 --bandwidth 限制傳輸速率(例如:500Kbit/s):
udp-sender --file C:\path\to\your\file.txt --dest 192.168.1.2:9000 --bandwidth 500Kbit
發送多個檔案 :
使用多個 --file 參數:
udp-sender --file C:\path\to\file1.txt --file C:\path\to\file2.txt --dest 192.168.1.2:9000
自定義端口 :
udp-sender --file C:\path\to\your\file.txt --dest 192.168.1.2:8888
傳送後自動結束 :
傳送完畢後自動結束
使用 --exit 參數:
udp-sender --file C:\path\to\your\file.txt --dest 192.168.1.2:9000 --exit
使用 --test 進行連接測試:
udp-sender --file C:\path\to\your\file.txt --dest 192.168.1.2:9000 --test
接收單個檔案
udp-receiver --file received_file.txt
使用自定義端口接收
如果發送端使用了不同的端口(例如:8888):
udp-receiver --file received_file.txt --port 8888
接收多個檔案
使用 --file 參數多次接收:
udp-receiver --file received_file1.txt --file received_file2.txt
指定接收檔案的目錄
將接收的檔案存儲到特定目錄:
udp-receiver --file C:\path\to\destination\received_file.txt
測試接收連接
在接收之前進行連接測試:
udp-receiver --test
監控接收進度
使用 --progress 顯示接收進度:
udp-receiver --file received_file.txt --progress
限制接收文件的大小
使用 --file-size 指定最大接收檔案大小(例如:100MB):
udp-receiver --file received_file.txt --file-size 100M
允許同時接收多個檔案
使用 --multicast 參數接收多個來源:
udp-receiver --file received_file.txt --multicast
要在區域網路中實現發送端在傳輸前先通知接收端要接收哪些檔案,可以考慮以下步驟:
發送端準備:
在發送端,列出需要傳輸的檔案或資料夾,並將這些檔案的清單寫入一個文本檔(例如:file_list.txt)。
plaintext
複製程式碼
C:\path\to\your\file1.txt
C:\path\to\your\file2.txt
C:\path\to\your\directory\
接收端設定:
接收端在接收資料之前需要啟動一個簡單的伺服器,以便接收發送端發出的通知。
可以使用 Python 或其他語言編寫一個簡單的 TCP 客戶端和伺服器來進行確認。
接收端(伺服器)
python
複製程式碼
import socket
# 設定接收端的IP和端口
HOST = '0.0.0.0' # 接收所有地址
PORT = 65432 # 自定義端口
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print("等待發送端連接...")
conn, addr = s.accept()
with conn:
print(f"連接來自 {addr}")
# 接收檔案清單
data = conn.recv(1024).decode()
print(f"接收到檔案清單:\n{data}")
# 確認接收
conn.sendall(b'確認接收檔案清單')
發送端(客戶端)
python
複製程式碼
import socket
# 設定接收端的IP和端口
HOST = '192.168.1.2' # 接收端的IP
PORT = 65432 # 自定義端口
# 讀取檔案清單
with open('file_list.txt', 'r') as f:
file_list = f.read()
# 連接接收端並發送檔案清單
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(file_list.encode())
confirmation = s.recv(1024)
print(f"接收到確認:{confirmation.decode()}")
# 接下來開始傳輸檔案
在確認接收端準備好接收檔案後,你可以再使用 UDPcast 進行資料的傳輸,根據之前的範例執行:
bash
複製程式碼
udp-sender --file C:\path\to\your\file1.txt --dest 192.168.1.2:9000
udp-sender --file C:\path\to\your\file2.txt --dest 192.168.1.2:9000
確保發送端和接收端的防火牆設定允許相應的 TCP 和 UDP 端口。
可以根據需要擴展上述 Python 腳本,例如在接收端處理多個檔案的接收。
這樣你就能夠在傳輸前進行確認,確保兩端的溝通順暢!如果有進一步的問題,隨時告訴我!
113.09.27
要在區域網路中實現一個具有 UI 界面的發送端,能夠選擇要傳輸的檔案或資料夾,並在確認連接後再進行傳輸,這裡有一個整體的實作方案:
你可以使用 Python 的 Tkinter 庫來建立簡單的圖形介面。以下是發送端的示例程式碼,讓使用者選擇要傳輸的檔案或資料夾,並發送檔案清單給接收端。
發送端(使用 Tkinter 的 GUI)
import tkinter as tk
from tkinter import filedialog, messagebox
import socket
import os
# 設定接收端的 IP 和端口
HOST = '192.168.1.2' # 接收端的 IP
PORT = 65432 # 自定義端口
def select_files():
files = filedialog.askopenfilenames(title="選擇要傳輸的檔案")
if files:
file_list.delete(0, tk.END) # 清除現有檔案清單
for file in files:
file_list.insert(tk.END, file)
def send_file_list():
if file_list.size() == 0:
messagebox.showwarning("警告", "請選擇檔案!")
return
# 構建檔案清單
files = [file_list.get(i) for i in range(file_list.size())]
file_list_str = "\n".join(files)
# 連接接收端並發送檔案清單
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((HOST, PORT))
s.sendall(file_list_str.encode())
confirmation = s.recv(1024).decode()
messagebox.showinfo("確認", confirmation)
start_file_transfer(files) # 開始檔案傳輸
except Exception as e:
messagebox.showerror("錯誤", f"連接失敗:{e}")
def start_file_transfer(files):
for file in files:
os.system(f"udp-sender.exe --file \"{file}\" --dest {HOST}:9000")
# 建立 GUI
root = tk.Tk()
root.title("檔案傳輸")
file_list = tk.Listbox(root, width=50)
file_list.pack(pady=20)
select_button = tk.Button(root, text="選擇檔案", command=select_files)
select_button.pack(pady=5)
send_button = tk.Button(root, text="發送檔案清單", command=send_file_list)
send_button.pack(pady=5)
root.mainloop()
接收端仍然需要使用 TCP 來接收檔案清單,然後再使用 UDP 接收檔案。這個程式碼跟之前的相似,只需確保在接收完檔案清單後開始使用 udp-receiver.exe 接收檔案。
接收端(伺服器)
import socket
import os
HOST = '0.0.0.0' # 接收所有地址
PORT = 65432 # 自定義端口
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print("等待發送端連接...")
conn, addr = s.accept()
with conn:
print(f"連接來自 {addr}")
data = conn.recv(1024).decode()
print(f"接收到檔案清單:\n{data}")
# 確認接收
conn.sendall(b'確認接收檔案清單')
# 開始接收檔案
for file in data.splitlines():
os.system(f"udp-receiver.exe --file \"{file}\"")
確保在發送端和接收端使用的 UDP 傳輸命令(udp-sender.exe 和 udp-receiver.exe)都已經正確配置,並且兩台電腦的防火牆允許相應的端口。
確保兩台電腦在同一個網路中並可以互相連接。
使用 TCP 來傳遞檔案清單,這樣可以確保傳輸的可靠性。
在發送檔案前,確認接收端已經啟動並準備好接收。
這樣,你就能夠使用 UI 界面選擇檔案,並在確認後使用 UDP 進行實際的檔案傳輸!如果有進一步的問題或需要調整,隨時告訴我!
如果在區網中,要如何讓發送資料端在網路先主動告知接收端要接收那些檔案或資料夾,發送端可以使用ui界面選擇要傳輸的資料,直接使用發送端的IP伺服端主機,兩邊確認連接後再進行傳輸?傳輸與接分別使用udp-sender.exe及upd-receiver.exe來達成?
當然可以!以下是針對 Windows 11 環境的完整發送端和接收端程式,分別使用 udp-sender.exe 和 udp-receiver.exe 來進行檔案傳輸。
python
複製程式碼
import socket
import os
import time
def send_file(file_path, receiver_ip, receiver_port):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# 發送檔案名稱
file_name = os.path.basename(file_path)
s.sendto(file_name.encode(), (receiver_ip, receiver_port))
# 等待接收端的確認
confirmation, _ = s.recvfrom(1024)
if confirmation.decode() == 'OK':
print("開始傳輸檔案...")
with open(file_path, 'rb') as f:
chunk = f.read(1024) # 每次讀取1KB
while chunk:
s.sendto(chunk, (receiver_ip, receiver_port))
chunk = f.read(1024)
print("檔案傳輸完成")
# 傳送結束標誌
s.sendto(b'', (receiver_ip, receiver_port)) # 發送空資料表示結束
else:
print("接收端未準備好")
if __name__ == "__main__":
receiver_ip = input("請輸入接收端IP地址: ")
file_path = input("請輸入要傳輸的檔案路徑: ")
receiver_port = 12345 # 可以自定義端口號
send_file(file_path, receiver_ip, receiver_port)
python
複製程式碼
import socket
def receive_file(receiver_port):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind(('', receiver_port))
print(f"接收端啟動,等待檔案傳輸...")
# 接收檔案名稱
file_name, addr = s.recvfrom(1024)
s.sendto(b'OK', addr) # 發送確認
print(f"接收到檔案名稱: {file_name.decode()}")
# 開始接收檔案
with open(file_name.decode(), 'wb') as f:
while True:
chunk, _ = s.recvfrom(1024)
if not chunk:
break
f.write(chunk)
print("檔案接收完成")
if __name__ == "__main__":
receiver_port = 12345 # 必須與發送端的端口相同
receive_file(receiver_port)
安裝 Python: 確保您的 Windows 11 上已安裝 Python。可以從 Python 官方網站 下載和安裝。
保存程式碼:
將發送端程式保存為 udp-sender.py。
將接收端程式保存為 udp-receiver.py。
運行接收端:
打開命令提示符或 PowerShell,導航到保存 udp-receiver.py 的目錄,並運行以下命令:
bash
複製程式碼
python udp-receiver.py
運行發送端:
在另一個命令提示符或 PowerShell 窗口,導航到保存 udp-sender.py 的目錄,並運行以下命令:
bash
複製程式碼
python udp-sender.py
按提示輸入接收端的 IP 地址和要傳輸的檔案路徑。
防火牆設置: 確保允許使用的端口(如 12345)在防火牆中開放,否則可能會阻止傳輸。
UDP 的可靠性: 請注意,UDP 本身不保證資料的送達,您可以在必要時考慮添加重傳機制或使用 TCP。
這樣就完成了使用 UDP 傳輸檔案的基本實現!如果有其他問題或需要進一步的功能,隨時告訴我!
發送端 (udp-sender.py),能改成讓使用者改成UI界面來選擇檔案並呈現檔案傳輸的狀態,此狀況包含檔案名稱、檔案大小使用14的紅色字體,用繁體中文
import socket
import os
import tkinter as tk
from tkinter import filedialog, messagebox
def send_file():
file_path = filedialog.askopenfilename()
if not file_path:
return
receiver_ip = entry_ip.get()
receiver_port = 12345 # 可以自定義端口號
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
label_status.config(text=f"檔案名稱: {file_name}\n檔案大小: {file_size} bytes", fg="red")
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# 發送檔案名稱
s.sendto(file_name.encode(), (receiver_ip, receiver_port))
# 等待接收端的確認
confirmation, _ = s.recvfrom(1024)
if confirmation.decode() == 'OK':
label_status.config(text=f"開始傳輸檔案: {file_name}...")
with open(file_path, 'rb') as f:
chunk = f.read(1024) # 每次讀取1KB
while chunk:
s.sendto(chunk, (receiver_ip, receiver_port))
chunk = f.read(1024)
label_status.config(text="檔案傳輸完成", fg="green")
# 傳送結束標誌
s.sendto(b'', (receiver_ip, receiver_port)) # 發送空資料表示結束
else:
messagebox.showerror("錯誤", "接收端未準備好")
# 創建主窗口
root = tk.Tk()
root.title("檔案傳輸工具")
root.geometry("400x300")
# IP 地址輸入框
tk.Label(root, text="接收端 IP 地址:").pack(pady=10)
entry_ip = tk.Entry(root)
entry_ip.pack(pady=10)
# 按鈕用於選擇檔案並傳輸
btn_send = tk.Button(root, text="選擇檔案並傳輸", command=send_file)
btn_send.pack(pady=20)
# 狀態顯示標籤
label_status = tk.Label(root, text="", font=("Arial", 14))
label_status.pack(pady=20)
# 啟動主循環
root.mainloop()
當然可以!若要使用 udp-sender.exe 和 udp-receiver.exe 來進行檔案傳輸,您可以按照以下步驟進行設計。
由於您希望使用 udp-sender.exe,這裡將修改程式碼,使用 Python 的 subprocess 模組來調用這些可執行檔案。
python
複製程式碼
import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess
import os
def send_file():
file_path = filedialog.askopenfilename()
if not file_path:
return
receiver_ip = entry_ip.get()
receiver_port = entry_port.get() or "12345" # 默認端口號
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
label_status.config(text=f"檔案名稱: {file_name}\n檔案大小: {file_size} bytes", fg="red")
# 構建命令行指令
command = f"udp-sender.exe {receiver_ip} {receiver_port} {file_path}"
try:
# 執行命令
process = subprocess.Popen(command, shell=True)
label_status.config(text="開始傳輸檔案...")
process.wait() # 等待傳輸完成
label_status.config(text="檔案傳輸完成", fg="green")
except Exception as e:
messagebox.showerror("錯誤", str(e))
# 創建主窗口
root = tk.Tk()
root.title("檔案傳輸工具")
root.geometry("400x300")
# IP 地址輸入框
tk.Label(root, text="接收端 IP 地址:").pack(pady=10)
entry_ip = tk.Entry(root)
entry_ip.pack(pady=10)
# 端口號輸入框
tk.Label(root, text="接收端端口號:").pack(pady=10)
entry_port = tk.Entry(root)
entry_port.pack(pady=10)
# 按鈕用於選擇檔案並傳輸
btn_send = tk.Button(root, text="選擇檔案並傳輸", command=send_file)
btn_send.pack(pady=20)
# 狀態顯示標籤
label_status = tk.Label(root, text="", font=("Arial", 14))
label_status.pack(pady=20)
# 啟動主循環
root.mainloop()
您需要確保接收端使用 udp-receiver.exe 來接收檔案。在這個情境下,您只需直接運行 udp-receiver.exe。
下載可執行檔:
從 udpcast 官方網站 下載 udp-sender.exe 和 udp-receiver.exe,並將它們放在與 udp-sender.py 相同的目錄下。
保存程式碼: 將更新後的發送端程式保存為 udp-sender.py。
運行接收端:
在命令提示符或 PowerShell 中,導航到 udp-receiver.exe 所在的目錄,並運行:
bash
複製程式碼
udp-receiver.exe
運行發送端:
在另一個命令提示符或 PowerShell 窗口,導航到保存 udp-sender.py 的目錄,並運行:
bash
複製程式碼
python udp-sender.py
使用介面:
在彈出的窗口中,輸入接收端的 IP 地址和端口號(默認為 12345),然後按下「選擇檔案並傳輸」按鈕。
選擇要傳輸的檔案,傳輸狀態將在介面中顯示。
確保防火牆設置允許 UDP 流量通過所使用的端口。
確保接收端已啟動並準備好接收檔案。
這樣就可以使用 udp-sender.exe 來實現檔案的傳輸了!如果有其他問題或需求,隨時告訴我!
使用繁體中文,在win11環境下,要在區域網路中實現一個具有 UI 界面的發送端,這個發送端在啟動後要能先接收到在區域網路中接受端的電腦的IP位置、MAC位置、電腦名稱,並確認可以啟動傳輸環境後,發送端能夠選擇要傳輸的檔案或資料夾,並在確認接受端電腦確認要接收的檔案或資料夾後再進行傳輸,傳送檔案的方式,要用"https://www.udpcast.linux.lu/exe.html",這個網站提供的udp-sender.exe及upd-receiver.exe來達成
使用繁體中文,在win11環境下,要在區域網路中實現一台電腦對多台電腦同時發送傳輸檔案或是資料夾,發送端需有 UI 界面,接收端也需要有UI界面,傳送檔案的方式,要用"https://www.udpcast.linux.lu/exe.html",這個網站提供的udp-sender.exe及upd-receiver.exe來達成
發送端能夠選擇要傳輸的檔案或資料夾
這個發送端在啟動後要能先接收到在區域網路中接受端的電腦的IP位置、MAC位置、電腦名稱,並確認可以啟動傳輸環境後,發送端能夠選擇要傳輸的檔案或資料夾,並在確認接受端電腦確認要接收的檔案或資料夾後再進行傳輸,傳送檔案的方式,要用"https://www.udpcast.linux.lu/exe.html",這個網站提供的udp-sender.exe及upd-receiver.exe來達成
一個具有 UI 界面的發送端
當然可以!以下是完整的 Python 範例,包括發送端和接收端的 GUI 界面,可以實際使用來進行檔案傳輸。這個範例會包含基本的錯誤處理和進度條顯示。
python
複製程式碼
import socket
import tkinter as tk
from tkinter import filedialog, messagebox
import threading
def send_file():
file_path = filedialog.askopenfilename()
if not file_path:
return
try:
with open(file_path, 'rb') as f:
data = f.read()
# 發送 UDP 封包
sock.sendto(data, (ip_entry.get(), 12345))
messagebox.showinfo("發送成功", "檔案已成功發送!")
except Exception as e:
messagebox.showerror("發送失敗", str(e))
# 創建 GUI
root = tk.Tk()
root.title("檔案發送端")
ip_label = tk.Label(root, text="接收端 IP:")
ip_label.pack()
ip_entry = tk.Entry(root)
ip_entry.pack()
send_button = tk.Button(root, text="選擇檔案並發送", command=send_file)
send_button.pack()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
root.mainloop()
python
複製程式碼
import socket
import tkinter as tk
from tkinter import messagebox
import threading
def receive_file():
while True:
data, addr = sock.recvfrom(65507) # 最大 UDP 封包大小
with open('received_file', 'wb') as f:
f.write(data)
messagebox.showinfo("接收成功", f"檔案已從 {addr} 接收!")
# 創建 GUI
root = tk.Tk()
root.title("檔案接收端")
receive_button = tk.Button(root, text="開始接收檔案", command=lambda: threading.Thread(target=receive_file, daemon=True).start())
receive_button.pack()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 12345)) # 接收任意 IP 的封包
root.mainloop()
安裝 Python: 確保你已經安裝了 Python 3.x。如果沒有,請從 Python 官方網站 下載並安裝。
保存程式碼: 將上述發送端程式碼保存為 sender.py,將接收端程式碼保存為 receiver.py。
執行接收端:
在所有希望接收檔案的電腦上,運行 receiver.py。點擊「開始接收檔案」按鈕以開始等待接收檔案。
執行發送端:
在發送檔案的電腦上,運行 sender.py。輸入接收端的 IP 地址(可以在接收端的 GUI 界面中找到)並選擇要發送的檔案。
防火牆設置: 確保所有電腦的防火牆設置允許 UDP 通訊,特別是端口 12345。
檔案大小限制: UDP 有封包大小的限制(通常是 65,507 字節),如果檔案較大,建議使用分段傳輸。
錯誤處理: 此範例中已經添加了一些基本的錯誤處理,若發生錯誤會顯示錯誤訊息。
進階功能: 若需要更多功能,如進度條、支持多檔案等,可以進一步擴展程式碼。
如果有其他問題或需要更多功能,請隨時告訴我!
能修正發送端及接收端的程式,傳送檔案的方式,使用"https://www.udpcast.linux.lu/exe.html",這個網站提供的udp-sender.exe及upd-receiver.exe來達成,能修正程式嗎?
ChatGPT 說:
ChatGPT
要使用 udp-sender.exe 和 udp-receiver.exe 來進行檔案傳輸,我們可以透過 Python 的 subprocess 模組來呼叫這些執行檔,而不是直接使用 socket 來傳輸檔案。以下是修正後的發送端和接收端程式碼範例。
下載 UDP Cast 工具:
前往 UDP Cast 官方網站 下載 udp-sender.exe 和 udp-receiver.exe,並將它們放在與 Python 程式相同的資料夾中。
python
複製程式碼
import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess
def send_file():
file_path = filedialog.askopenfilename()
if not file_path:
return
ip_address = ip_entry.get()
if not ip_address:
messagebox.showerror("錯誤", "請輸入接收端 IP 地址!")
return
# 構造命令行
command = ['udp-sender.exe', '-n', '1', ip_address, '12345', file_path]
try:
# 使用 subprocess 呼叫外部程序
subprocess.run(command, check=True)
messagebox.showinfo("發送成功", "檔案已成功發送!")
except subprocess.CalledProcessError as e:
messagebox.showerror("發送失敗", str(e))
# 創建 GUI
root = tk.Tk()
root.title("檔案發送端")
ip_label = tk.Label(root, text="接收端 IP:")
ip_label.pack()
ip_entry = tk.Entry(root)
ip_entry.pack()
send_button = tk.Button(root, text="選擇檔案並發送", command=send_file)
send_button.pack()
root.mainloop()
python
複製程式碼
import tkinter as tk
from tkinter import messagebox
import subprocess
def receive_file():
# 構造命令行
command = ['udp-receiver.exe', '-p', '12345']
try:
# 使用 subprocess 呼叫外部程序
subprocess.run(command, check=True)
messagebox.showinfo("接收成功", "檔案已成功接收!")
except subprocess.CalledProcessError as e:
messagebox.showerror("接收失敗", str(e))
# 創建 GUI
root = tk.Tk()
root.title("檔案接收端")
receive_button = tk.Button(root, text="開始接收檔案", command=receive_file)
receive_button.pack()
root.mainloop()
安裝 Python: 確保你已經安裝了 Python 3.x。如果沒有,請從 Python 官方網站 下載並安裝。
保存程式碼: 將發送端程式碼保存為 sender.py,將接收端程式碼保存為 receiver.py。
將 UDP Cast 工具放在相同資料夾: 確保 udp-sender.exe 和 udp-receiver.exe 在與 sender.py 和 receiver.py 相同的資料夾中。
執行接收端:
在所有希望接收檔案的電腦上,運行 receiver.py。點擊「開始接收檔案」按鈕以開始等待接收檔案。
執行發送端:
在發送檔案的電腦上,運行 sender.py。輸入接收端的 IP 地址,然後選擇要發送的檔案。
防火牆設置: 確保所有電腦的防火牆設置允許 UDP 通訊,特別是端口 12345
使用繁體中文,在W11下,"udp-sender.exe -h C:\Windows\system32\udp-sender.exe: unknown option -- h C:\Windows\system32\udp-sender.exe [--file file] [--full-duplex] [--pipe pipe] [--portbase portbase] [--blocksize size] [--interface net-interface] [--mcast-data-address data-mcast-address] [--mcast-rdv-address mcast-rdv-address] [--max-bitrate bitrate] [--pointopoint|--nopointopoint] [--async] [--log file] [--no-progress] [--min-slice-size min] [--max-slice-size max] [--slice-size] [--ttl time-to-live] [--fec <stripes>x<redundancy>/<stripesize>] [--print-seed] [--rexmit-hello-interval interval] [--autostart autostart] [--broadcast] [--min-receivers receivers] [--min-wait sec] [--max-wait sec] [--start-timeout n] [--retries-until-drop n] [--nokbd] [--bw-period n] [--streaming] [--rehello-offset offs][--license] PS C:\Users\fspsteacher>",能說明以上這個指令的各種用法嗎,另能給使用範例嗎?
使用繁體中文,在w11下," udp-receiver.exe -h C:\Windows\system32\udp-receiver.exe: unknown option -- h C:\Windows\system32\udp-receiver.exe [--file file] [--pipe pipe] [--portbase portbase] [--interface net-interface] [--log file] [--no-progress] [--ttl time-to-live] [--mcast-rdv-address mcast-rdv-address] [--rcvbuf buf] [--nokbd] [--exit-wait milliseconds] [--nosync] [--sync] [--start-timeout sto] [--receive-timeout rct] [--license] [-x uncomprStatPrint] [-z statPeriod] [--print-uncompressed-position flag] [--stat-period millis] [--ignore-lost-data]",能說明以上這個指令的各種用法嗎?