【问题标题】:Bind multiple listener to the same port将多个监听器绑定到同一个端口
【发布时间】:2014-05-13 16:20:14
【问题描述】:

我在.net 3.5 中使用UdpClient 类 我需要将多个应用程序绑定到同一个端口。

所以,如果UDP 服务器广播任何请求 - 所有在端口上侦听的应用程序都可以接收消息,但问题是,当我尝试将应用程序绑定到同一端口时,只有一个应用程序接收到消息并且另一个没有。

以下是这两个应用程序的一些示例代码:

    UdpClient udpClient = new UdpClient();
    Thread thread;
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 11000);
    public Form1()
    {
        //CheckForIllegalCrossThreadCalls = false;

        InitializeComponent();
        udpClient.ExclusiveAddressUse = false;
        udpClient.Client.SetSocketOption(
        SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpClient.Client.Bind(endPoint);
    }

    private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            thread.Abort();
            udpClient.Close();
            Close();
        }
    }

    private void ReceiveMessage()
    {
        //while (true)
        //{
        // IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 11000);
        //  byte[] content = udpClient.Receive(ref endPoint);
        udpClient.BeginReceive(new AsyncCallback(Read_Callback), null);

        //if (content.Length > 0)
        //{
        //    string message = Encoding.ASCII.GetString(content);

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

    public void Read_Callback(IAsyncResult ar)
    {
        try
        {
            byte[] buffer = udpClient.EndReceive(ar, ref endPoint);
            // Process buffer
            string s = Encoding.ASCII.GetString(buffer);
            // richTextBox1.Text = s;
            udpClient.BeginReceive(new AsyncCallback(Read_Callback), null);

        }
        catch (Exception ex)
        { }
    }

PS:我无法弄清楚原因或者我错过了什么。 ?

【问题讨论】:

    标签: c# udpclient


    【解决方案1】:

    这就是套接字的本质。即使在多个应用程序可以访问同一个端口的情况下(例如 UDP),数据也是先到先得的。 UDP 的设计开销也最小,因此甚至没有机会像您(假设)使用 TCP 那样“检查队列”。

    它旨在让多个进程共享服务器负载,根据谁空闲来交替接收请求。

    您需要构建一些外部的东西来解决这个问题,例如重传协议或数据库,以确保每个入站消息都是共享的。

    如果您可以处理这些更改,处理此问题的更智能方法是 UDP 多播,其中多个程序本质上注册以接收组消息。在这种情况下,可以(并且应该)放弃单端口限制。

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2013-12-26
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      相关资源
      最近更新 更多