如何更改UdpClient IP地址?
有没有办法动态更改 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();
...
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();
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要一些时间来启动线程并停止,然后才能调用
StartUpd
和StopUpd
。关闭
UDP 客户端后,您可以等待线程退出。这将确保在您尝试重新连接之前其已关闭。所以代码会像这样:其他随机注释,看起来你拼错了函数名称,可能应该是
StartUdp
和StopUdp
You'll need some time for the thread to start, and to stop before you can call
StartUpd
andStopUpd
. You can wait for the thread to exit once youClose
the UDP client. This will ensure that its closed before you try to reconnect. So the code would like something like this:Other random note, looks like you misspelled the function names, probably should be
StartUdp
andStopUdp
您正在从调用 Connect 方法的设置中设置 IP 和端口。尝试使用不同的 ip 和端口再次调用连接。
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.
对 Connect 的调用会建立 UdpClient 连接的默认远程地址,这意味着您不必在调用
Send
方法时指定此地址。这段代码确实不会导致您看到的错误。此错误是尝试使用两个客户端侦听同一端口的结果,这使我相信实际上可能是您的 UdpReceiveThread 才是问题所在。您可以在 UdpClient 的构造函数中指定要绑定的本地端口/地址。
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.