Home > Software design >  UDP behavior goes wrong when using two identical scripts in Unity
UDP behavior goes wrong when using two identical scripts in Unity

Time:09-22

I attached two of the following scripts to a single GameObject.

using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class TestScript : MonoBehaviour
{
    static UdpClient udp;
    private string udp_message = "";
    Thread thread;
    public int port = 8888;

    void Start()
    {
        udp = new UdpClient(port);

        thread = new Thread(new ThreadStart(ThreadMethod));
        thread.Start();
    }

    // Update is called once per frame
    void Update()
    {
        string port_string = port.ToString();
        Debug.Log(port_string   ":"   udp_message);
    }

    void ThreadMethod()
    {
        while (true)
        {
            try
            {
                IPEndPoint remoteEP = null;
                byte[] data = udp.Receive(ref remoteEP);
                udp_message = Encoding.ASCII.GetString(data);
            }
            catch
            {
            }
        }
    }
}

Then, I used 8888 as the port for one script, as shown in the following image. The other script used port 8889.

enter image description here

I am using two different ports on 8888 and 8889.

However, when I send data to only the 8888 port, the UDP on the 8889 port also seems to be responding.

What is the cause of this?

How can I fix it?

CodePudding user response:

Well your udp field is static!

Both instances of your component overwrite it with different references in

udp = new UdpClient(port);

So basically whichever script runs last "wins" and you are only ever using that UdpClient instance.

Later both your threads will access the very same udp reference for doing

udp.Receive(...);

Simply do not make you field static and you should be fine ^^

private UdpClient udp;

And to your empty catch block ... I would at least make it

catch(Exception e)
{
    Debug.LogException(e);
}

which displays an error in the console but doesn't interrupt the thread.


And then also make sure to clean up!

private void OnDestroy()
{
    thread?.Abort();
    udp?.Dispose();
}

otherwise you might end up with zomby threads or blocked UDP ports ;)

  • Related