2014-04-02 137 views
3

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

因此,如果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:我无法弄清楚的原因还是我失去了一些东西。 ?

回答

3

这是插座的本质。即使在多个应用程序可以访问相同端口的情况下(例如UDP),数据也会先发送,先到先服务。 UDP的设计开销最小,所以甚至没有机会“检查队列”,就像你(假设)可以通过TCP一样。

它是围绕具有多进程设计共享服务器负载,交替谁接收基于谁是空闲的请求。

你需要建立一些外部来解决这个问题,就像一个重传协议或数据库,以确保每一个入站信息共享。

如果你能处理的变化,一个更聪明的方式来处理,这将是UDP Multicast,其中多个节目基本注册,以接收群消息。在这种情况下,单端口限制可以(也应该)被放弃。

+0

感谢链接帮助了我很多... –