2011-09-27 270 views
1

有没有办法在运行中更改UdpClient IP地址?即使做了StopUpd()后每个套接字 地址(协议/网络地址/端口)中的一个的使用通常允许如何更改UdpClient IP地址?

StartUpd()抛出一个

System.Net.Sockets.SocketException。

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(); 
     ... 

回答

2

您需要一段时间才能启动线程,并在您拨打StartUpdStopUpd之前停止。您可以等待该线程退出,一旦您的UDP客户端为Close。这将确保它在尝试重新连接之前关闭。因此,代码想是这样的:

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

2

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

1

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

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