[英]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 上沒有圖形用戶界面):
請問核心版Broadcaster有什么問題? 我是否需要更改它,或者告訴 Linux“嘿這個應用程序允許廣播,或者什么”? Mono 與 Core 有何不同?
與本機套接字 API 通話時,不同的實現設置不同的默認值。因此,在您的情況下,您應該將UdpClient.EnableBroadcast
設置為true
,以便 .NET Core 可以發送廣播請求。
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.