带Unity C#UDP接收的SocketException
我正在使用Unity,我正在尝试侦听UDP数据包在特定端口上传入。在Unity中,我有一个附加了脚本的对象,该脚本被设计为只监听和记录来自UDP数据包的数据。在脚本中,我有启动功能:带Unity C#UDP接收的SocketException,c#,sockets,exception,udp,C#,Sockets,Exception,Udp,我正在使用Unity,我正在尝试侦听UDP数据包在特定端口上传入。在Unity中,我有一个附加了脚本的对象,该脚本被设计为只监听和记录来自UDP数据包的数据。在脚本中,我有启动功能: public void Start() { // Setup listener. this.mListener = new IPEndPoint(IPAddress.Loopback, 0); // Setup background UDP listener thread. t
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.
/* REDACTED */
// Separate out the data.
/* REDACTED */
// Store data in the DataSource.
/* REDACTED */
} 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属性有关…好吧,我在代码中没有看到任何明显的问题,但在调用
IPEndPoint
函数时,请尝试将IPAddress.Loopback
更改为IPAddress.Any
。我想我没有提到我在发布此函数之前尝试过此操作,但运气不佳。一、 幸运的是,通过将UdpClient从使用单独的线程改为使用异步回调,解决了我的问题。尽管如此,我还是不知道为什么这个代码不能工作。