我正在使用Unity,我正在嘗試收聽特定端口上的UDP資料包 . 在Unity中,我有一個附加腳本的對象,該腳本旨在簡單地監聽和記錄UDP資料包中的資料 . 在腳本中我有我的啟動功能:
public void Start() {
// Setup listener.
this.mListener = new IPEndPoint(IPAddress.Loopback, 0);
// Setup background UDP listener thread.
this.mReceiveThread = new Thread(new ThreadStart(ReceiveData));
this.mReceiveThread.IsBackground = true;
this.mReceiveThread.Start();
}
該函數設定IPEndPoint和接收線程,然後啟動接收線程,定義為:
private void ReceiveData() {
try {
// Setup UDP client.
this.mClient = new UdpClient(30020);
this.mClient.Client.ReceiveTimeout = 250;
// While thread is still alive.
while(Thread.CurrentThread.IsAlive) {
try {
// Grab the data.
byte[] data = this.mClient.Receive(ref this.mListener);
// Convert the data.
// Separate out the data.
// Store data in the DataSource.
} catch(SocketException e) {
Debug.Log(e.ToString());
continue;
}
}
} catch(Exception e) {
Debug.Log(e.ToString());
}
}
但是,當我嘗試運作它時,我不斷收到以下SocketException:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
這段代碼工作了幾個月,我對我真的很有意義 . 我似乎沒有任何影響 . 我不确定發生了什麼,或者我做了什麼改變使它表現得這樣 . 自從我開始這個項目以來,我沒有更新Unity . 我的其他程式可能不會發送任何UDP資料包嗎?缺少UDP資料包可能是導緻這種情況的原因嗎?此SocketException在我的日志中出現的頻率與ReceiveTimeout屬性有關...