1

有没有办法即时更改 UdpClient IP 地址? StartUpd()抛出一个

System.Net.Sockets.SocketException:每个套接字地址(协议/网络地址/端口)通常只允许使用一次

即使在做了一个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();
        ...
4

3 回答 3

2

您正在从调用 Connect 方法的设置中设置 ip 和端口。尝试使用不同的 ip 和端口再次调用连接。

于 2011-09-27T19:07:11.427 回答
2

您需要一些时间来启动和停止线程,然后才能调用StartUpdand StopUpdClose一旦您使用 UDP 客户端,您就可以等待线程退出。这将确保它在您尝试重新连接之前关闭。所以代码会是这样的:

  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); }
  }

其他随机注释,看起来你拼错了函数名称,可能应该是StartUdpStopUdp

于 2011-09-27T21:04:04.510 回答
1

对 Connect 的调用建立了 UdpClient 连接到的默认远程地址,这意味着您不必在调用该Send方法时指定此地址。此代码实际上不应该导致您看到的错误。此错误是尝试使用两个客户端在同一端口上侦听的结果,这使我相信这可能是您的 UdpReceiveThread 实际上是这里的问题。

您可以在 UdpClient 的构造函数中指定要绑定到的本地端口/地址。

于 2011-09-27T19:30:29.463 回答