1

Is there a way to change the UdpClient IP address on the fly? StartUpd() throws a

System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted

even after doing a StopUpd().

private static UdpClient udpClientR;
void StartUpd()
{
    try
    {
        udpClientR = new UdpClient();
        udpClientR.Connect(Settings.rxIPAddress, PORT_RX_LOCAL);
        var t1 = new Thread(() => UdpReceiveThread(PORT_RX_REMOTE)) 
        { IsBackground = true };
        t1.Start();
        ...

private void StopUpd()
{
    try
    {
        udpClientR.Close();
        ...
jacknad
  • 13,483
  • 40
  • 124
  • 194

3 Answers3

2

You are setting ip and port from the settings in the call to Connect method. try to call the connect again with different ip and port.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
2

You'll need some time for the thread to start, and to stop before you can call StartUpd and StopUpd. You can wait for the thread to exit once you Close the UDP client. This will ensure that its closed before you try to reconnect. So the code would like something like this:

  private UdpClient udpClientR;
  private Thread t1;
  void StartUpd()
  {
     udpClientR = new UdpClient();
     udpClientR.Connect(Settings.rxIPAddress, PORT_RX_LOCAL);
     t1 = new Thread(() => UdpReceiveThread(PORT_RX_REMOTE)) { IsBackground = true };
     t1.Start();
     // Give it some time here to startup, incase you call StopUpd too soon
     Thread.Sleep(1000);
  }

  private void StopUpd()
  {
     udpClientR.Close();
     // Wait for the thread to exit.  Calling Close above should stop any
     // Read block you have in the UdpReceiveThread function.  Once the
     // thread dies, you can safely assume its closed and can call StartUpd again
     while (t1.IsAlive) { Thread.Sleep(10); }
  }

Other random note, looks like you misspelled the function names, probably should be StartUdp and StopUdp

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
1

The call to Connect establishes the default remote address to which the UdpClient connects, which means you do not have to specify this address in calls to the Send method. This code should really not cause the error you're seeing. This error is the result of trying to listen on the same port with two clients, which makes me believe that it might be your UdpReceiveThread that is actually the problem here.

You can specify the local port/address to bind to in the constructor of the UdpClient.

DeCaf
  • 6,026
  • 1
  • 29
  • 51