UDP绑定方法

本文关键字:方法 绑定 UDP | 更新日期: 2024-07-27 03:51:50

我正在尝试在两台计算机之间建立UDP通信链路。一台计算机正在运行客户端应用程序,另一台正在运行服务器应用程序。客户端应用程序给出错误:

执行此操作之前,必须调用Bind方法

下面是我为客户端编写的代码,我已经评论了错误发生的地方:

 public delegate void ShowMessage(string message);
    UdpClient udpClient = new UdpClient();
    Int32 port = 11000;
    public ShowMessage myDelegate;
    Thread thread;

private void Form1_Load(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(ReceiveMessage));
        thread.IsBackground = true;
        thread.Start();
    }

    private void ReceiveMessage()
    {
        while (true)
        {
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
            //Error on this line
            byte[] content = udpClient.Receive(ref remoteIPEndPoint);
            if (content.Length > 0)
            {
                string message = Encoding.ASCII.GetString(content);

                this.Invoke(myDelegate, new object[] { message });
            }
        }
    }

如有任何帮助,我们将不胜感激。

来源->http://lamahashim.blogspot.com/2009/06/using-c-udpclient-send-and-receive.html

UDP绑定方法

我认为您需要首先在侦听服务器上调用Bind

udpServer.Client.Bind(new IPEndPoint(IPAddress.Any, 11000));

您需要告诉udpclient要监听哪个端口。您传递给receive方法的IPEndpoint可以设置为任何您喜欢的值,因为它会填充发送者的详细信息。它不指示udpclient侦听端口11000。实际上,您正在尝试侦听端口0,它指示udpclient选择自己的端口。

看看http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

您将看到使用要侦听的端口调用构造函数。

我遇到了这个问题,并试图用Bind解决,但这种方法有一个限制:

  • 创建udpClient后,可以使用Bind分配所需的IPEndPoint
  • 当您尝试再次将其他IPEndPoint分配给相同的udpClient后缀时,会出现问题:它会给出一个错误。我想这会发生在您作为示例编写的代码中(因为循环)。要解决这种情况,必须关闭udpClient udpClient.Close()并再次生成udpClient.new(),然后可以再次使用Bind方法并设计新的IPEndPoint

原因是Bind方法仅适用于具有IPEndPoint=null 的新udpClient

我希望它能有所帮助。

嗯。。我没有搜索太多。。但我用了这个,它起了作用:

UdpClientv4.Client.Connect(ipEndPointv4);

我使用了"连接"而不是"绑定"。可能是Connect正在调用Bind。