1

我正在使用 Unity,我正在尝试监听来自特定端口的 UDP 数据包。在 Unity 中,我有一个附加了脚本的对象,该脚本旨在简单地侦听和记录来自 UDP 数据包的数据。在脚本中,我有我的 Start 函数:

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 属性有关...

4

0 回答 0