我把下面的兩個腳本附在一個GameObject上。
using UnityEngine;
using System.Net;
using System.Net.Sockets;
public class TestScript : MonoBehaviour
{
static UdpClient udp;
private string udp_message = ""/span>;
執行緒執行緒。
public int port = 8888;
void Start()
{
udp = new UdpClient(port);
thread = new Thread(new ThreadStart(ThreadMethod))。
thread.Start()。
}
//Update每幀被呼叫一次。
void Update()
{
string port_string = port.ToString();
Debug.Log(port_string ":"/span> udp_message)。
}
void ThreadMethod()
{
while (true)
{
try(true)。
{
IPEndPoint remoteEP = null;
byte[] data = udp.Receive(ref remoteEP)。
udp_message = Encoding.ASCII.GetString(data)。
}
捕獲
{
}
}
}
}
然后,我把8888作為一個腳本的埠,如下圖所示。另一個腳本則使用了8889埠。
我在8888和8889上使用兩個不同的埠。
然而,當我只向 8888 埠發送資料時,8889 埠的 UDP 似乎也在回應。
這是什么原因?
我怎樣才能解決這個問題?
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
那么你的udp欄位是static!
你的兩個組件的實體都用不同的參考覆寫它
udp = new UdpClient(port)。
所以基本上哪個腳本最后運行就 "贏 "了,而且你只使用那個UdpClient實體。
以后你的兩個執行緒都將訪問相同的udp參考,以進行
udp.Receive(...)。
不要讓你的欄位變成靜態的,你應該會很好^^
private UdpClient udp。
而對于你的空的catch塊... 我至少會讓它
catch(Exception e)
{
Debug.LogException(e)。
}
這將在控制臺中顯示一個錯誤,但不會中斷執行緒。
然后還要確保進行清理!
private void OnDestroy()
{
thread?.Abort()。
udp?.Dispose()。
}
否則,你可能會出現Zomby執行緒或阻塞的UDP埠;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/329080.html
標籤:

