簡體   English   中英

廣播單聲道與核心

[英]Broadcast-Mono vs Core

我在 Linux 上觀察到一件奇怪的事情。下面的簡單代碼通過整個 LAN 進行廣播。 我將該簡單項目編譯為核心項目和/或 Mono 項目(均適用於 Linux)。 它們似乎工作正常,但只有從 Mono 編譯我才能捕獲 UDP 數據包,否則不能(使用 Core)。

public sealed class Broadcaster : IDisposable
{
   readonly IPEndPoint _ipEndPoint;
   readonly object _locker = new object();
   readonly Dictionary<string, UdpClient> _clients = new Dictionary<string, UdpClient>();

   public Broadcaster(ushort broadcastPort)
   {
       _ipEndPoint = new IPEndPoint(IPAddress.Broadcast, broadcastPort);
   }

   public void Send(string message)
   {
       var data = Encoding.ASCII.GetBytes(message);
       var host = Dns.GetHostEntry(Dns.GetHostName());
       var addressList = host.AddressList;
       var ip = addressList.Last();
       var ip_ = ip.ToString();
       lock (_locker)
       {
           if (!_clients.ContainsKey(ip_))
               _clients.Add(ip_, new UdpClient(new IPEndPoint(ip, 0)));
       }
       try
       {
           _clients[ip_].SendAsync(data, data.Length, _ipEndPoint);
           Console.WriteLine($"broadcast: {DateTime.UtcNow}");
       }
       catch (Exception ex)
       {
           Console.WriteLine($"unable to use host {ip} while broadcasting: " + ex);
       }
   }

   public void Dispose()
   {
       try
       {
           lock (_locker)
           {
               foreach (var client in _clients)
               {
                   client.Value.Close();
                   client.Value.Dispose();
               }
               _clients.Clear();
           }
       }
       catch (Exception ex)
       {
           Console.WriteLine("Network boadcaster finishing: " + ex);
       }
   }
}  

...及其用法:

static async Task Main(string[] args)
{
    var broadcaster = new Broadcaster(15015);
    while (true)
    {
        broadcaster.Send($"Broadcaster: { DateTime.UtcNow.ToString("HH:mm:ss.fff")}");
        await Task.Delay(1000);
    }
}

已經檢查過(bash - Linux 上沒有圖形用戶界面):

  • ufw 允許 15005/udp
  • 除了廣播接收應用程序(它可以很好地捕獲 Mono 廣播公司的數據包)之外的另一台計算機現在配備了 Wireshark,這正好證實了我的觀察。

請問核心版Broadcaster有什么問題? 我是否需要更改它,或者告訴 Linux“嘿這個應用程序允許廣播,或者什么”? Mono 與 Core 有何不同?

與本機套接字 API 通話時,不同的實現設置不同的默認值。因此,在您的情況下,您應該將UdpClient.EnableBroadcast設置為true ,以便 .NET Core 可以發送廣播請求。

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM