A very very strange problem

I am doing udpclient these days,
just want to get a UDPclient instance by a port number(int).
it sounds easy.
but I find a strange problem…and it problem take several days and still unsolved…

this my code:

  protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
    {
        pManager.AddIntegerParameter("LocalPort", "", "", GH_ParamAccess.item);
    }
    protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
    {
        pManager.AddGenericParameter("UDPClient", "", "", GH_ParamAccess.item);
    }
    UdpClient udpClient;
    int localPort;

    protected override void SolveInstance(IGH_DataAccess DA)
    {
        if (!DA.GetData("LocalPort", ref localPort))
        {
            return;
        }
        udpClient = new UdpClient(localPort);//put a breakpoint here
        DA.SetData("UDPClient", udpClient);
    }


the error message in English is:“Only one usage of each socket address(protocol/network address/port) is normally permitted “.
i use “netstate -a” to check the net socket usage ,i am sure every time the “59153"port is available to use before launch Rhino and grasshopper.
so I go to debug ,i add a break point at"udpClient = new UdpClient(localPort);”,then i find when this breakpoint is hit, i see the udpClient is null and then be given a newUdpClient(localPort) ,it is i want and nothing error happens when be given a newudpclient.so in normally,the solveinstance() should stop after " DA.SetData(“UDPClient”, udpClient);”…but no…when i press continue …the program stop at breakpoint second time!,so udpclient is null again!(it should be not null because already has been set),and it will be given again with same portNumber,this is the source of error"collision of port”.
I just donnot know why the solveinstance run twice …
(and i found solveinstance sometime run one time,and sometime run twice…)
Thank you for explain!

It seems you need to use some mechanism to check _udpClient status like this:

protected override void SolveInstance(IGH_DataAccess DA)
{
    var port = 0;
    if (DA.GetData(0, ref port))
    {
        if (_udpClient == null)
            _udpClient = new UdpClient(port);
        else if (((IPEndPoint)_udpClient.Client.LocalEndPoint).Port != port)
        {
            _udpClient.Close();
            _udpClient = new UdpClient(port);
        }
    }
    DA.SetData(0, _udpClient);
}


UDP.gha (6 KB)
UDP.zip (20.9 KB) (Source)
P.S. You will also need to check if another instance of this component with same LocalPort is on the canvas.

Thank you Mahdiyar
I tried your code,it also has the same problem…
the problem is the first time i create the file is ok like your image post,but after save this file and close rhino,and restart,reopen this gh file,the error again:


the problem is same ,the source of this error is mentioned above my post:the udp component run solveInstance Twist(i hope it just run once).
Thank you all the same