是否有办法动态更改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();
...发布于 2011-09-27 21:04:04
您需要一些时间来启动线程,并在调用StartUpd和StopUpd之前停止。一旦您Close 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); }
}其他随机注释,看起来您拼写错了函数名,可能应该是StartUdp和StopUdp。
发布于 2011-09-27 19:07:11
您正在从调用连接方法的设置中设置ip和端口。尝试用不同的ip和端口再次调用连接。
发布于 2011-09-27 19:30:29
对连接的调用建立了UdpClient连接到的默认远程地址,这意味着您不必在调用Send方法时指定此地址。这段代码不应该导致您所看到的错误。这个错误是试图在同一个端口上侦听两个客户端的结果,这使我相信可能是您的UdpReceiveThread才是问题所在。
可以在UdpClient的构造函数中指定要绑定到的本地端口/地址。
https://stackoverflow.com/questions/7574242
复制相似问题