在 WinForm 應用中,為避免 UI 凍結,通常另開一條執行緒持續監聽 UDP 封包:
private void listen()
{
while (true)
{
string text = Encoding.UTF8.GetString(uc.Receive(ref IEp));
lbInfo.Items.Add(text + "\n");
}
}
uc.Receive(ref IEp):封鎖式呼叫,直到收到資料為止,IEp 會回填發送端的 IPEndPoint。ListBox 顯示。lbInfo.Items.Clear();
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
th.Abort(); // 強制結束接收執行緒
uc.Close(); // 關閉 UdpClient
}
base.Dispose(disposing);
}
注意:Thread.Abort() 在 .NET Core/.NET 5+ 已過時,建議改用 CancellationToken 實作優雅停止。
public int Send(byte[] dgram, int bytes);
public int Send(byte[] dgram, int bytes, string hostname, int port);
public int Send(byte[] dgram, int bytes, IPEndPoint endPoint);
| 參數 | 說明 |
|---|---|
| dgram | 待發送的位元組陣列 |
| bytes | 實際發送長度(通常為 dgram.Length) |
| hostname/port | 目標主機名或 IP 與連接埠 |
| endPoint | 封裝好 IP 與 Port 的 IPEndPoint 物件 |
public byte[] Receive(ref IPEndPoint remoteEP);
remoteEP 為 ref 參數,呼叫後會包含發送端資訊,方便回覆。實際測試中,資料偶爾無法送達對端,這正是 UDP「無連線、不保證送達」的本質。若應用層需要可靠性,須自行實作確認與重傳機制(如序號、ACK、超時重送)。