Windows Phone 8.1不发送UDP广播

本文关键字:UDP 广播 Phone Windows | 更新日期: 2023-09-27 18:02:07

我正在尝试用Windows Phone 8.1发送UDP广播。因此,我创建了一个UDP服务器(一个控制台应用程序),它运行在我的笔记本电脑上,与我的WP8.1在相同的Wifi网络上。

这是测试服务器:

static void Main(string[] args)
{
    var client = new UdpClient(12345);
    client.MulticastLoopback = false;
    var isRunning = true;
    var thread = new Thread(() =>
    {
        while (isRunning)
        {
            var endpoint = new IPEndPoint(IPAddress.Any, 0);
            var data = client.Receive(ref endpoint);
            Console.WriteLine("Received message from {0}:{1} with length={2}", endpoint.Address, endpoint.Port, data.Length);
            client.Send(data, data.Length, endpoint);
        }
    });
    thread.Start();
    Console.ReadLine();
    isRunning = false;
}

当我创建另一个控制台应用程序发送一些数据作为UDP广播时,我将获得与服务器响应相同的数据。所以服务器工作正常。在Windows Phone 8.1中,我必须使用DatagramSocket。这是我的代码:

var socket = new DatagramSocket();
socket.MessageReceived += HandleIncomingMessages;
using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), "12345"))
{
    await stream.WriteAsync(data.AsBuffer());
    await stream.FlushAsync();
}

在创建socket对象后,我还尝试了一个额外的await _socket.ConnectAsync(new HostName("255.255.255.255"), "12345");

遗憾的是,我永远不会得到答案。

Windows Phone 8.1不发送UDP广播

这是我对支持广播的UdpClient的实现。

public class UdpClient : IDisposable
{
    private readonly DatagramSocket _socket;
    private readonly BlockingCollection<Tuple<IpAddress, byte[]>> _incomingMessages;
    private readonly IpAddress _ipAddress;
    private readonly object _lock = new object();
    private bool _isBound;
    private bool _isBinding;
    public UdpClient(IpAddress ipAddress)
    {
        _ipAddress = ipAddress;
        _socket = new DatagramSocket();
        _socket.Control.DontFragment = true;
        _incomingMessages = new BlockingCollection<Tuple<IpAddress, byte[]>>();
        _socket.MessageReceived += HandleIncomingMessages;
    }
    public async Task SendAsync(byte[] data)
    {
        try
        {
            await Connect();
            using (var stream = await _socket.GetOutputStreamAsync(_ipAddress.Host, _ipAddress.ServiceName))
            {
                await stream.WriteAsync(data.AsBuffer(0, data.Length));
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
        }
    }
    public bool TryGetIncomingMessage(out Tuple<IpAddress, byte[]> message)
    {
        return _incomingMessages.TryTake(out message, TimeSpan.FromMilliseconds(20));
    }
    public void Dispose()
    {
        _socket.Dispose();
    }
    private async Task Connect()
    {
        if (_isBound || _isBinding)
        {
            return;
        }
        lock (_lock)
        {
            if (_isBound || _isBinding)
            {
                return;
            }
            _isBinding = true;
        }
        var possibleConnectionProfiles = NetworkInformation.GetConnectionProfiles()
            .Where(p => p.IsWlanConnectionProfile && p.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)
            .ToList();
        var connectionProfile = possibleConnectionProfiles.FirstOrDefault();
        if (connectionProfile != null)
        {
            await _socket.BindServiceNameAsync(_ipAddress.ServiceName, connectionProfile.NetworkAdapter);
        }
        _isBound = true;
        _isBinding = false;
    }
    private void HandleIncomingMessages(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
    {
        var address = e.RemoteAddress.ToString();
        var port = int.Parse(e.RemotePort);
        using (var reader = e.GetDataReader())
        {
            var data = reader.DetachBuffer().ToArray();
            _incomingMessages.Add(Tuple.Create(new IpAddress(address, port), data));
        }
    }
}
public struct IpAddress
{
    public static readonly IpAddress Broadcast = new IpAddress("255.255.255.255");
    public readonly string Address;
    public readonly int Port;
    public readonly HostName Host;
    public readonly string ServiceName;
    public IpAddress(string address, int port)
    {
        Address = address;
        Port = port;
        Host = new HostName(address);
        ServiceName = port.ToString(CultureInfo.InvariantCulture);
    }
    public override string ToString()
    {
        return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", Address, Port);
    }
    public bool Equals(IpAddress other)
    {
        return string.Equals(Address, other.Address) && Port == other.Port;
    }
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
            return false;
        return obj is IpAddress && Equals((IpAddress)obj);
    }
    public override int GetHashCode()
    {
        unchecked
        {
            return ((Address != null ? Address.GetHashCode() : 0) * 397) ^ Port;
        }
    }
}

我读到广播消息到255.255.255.255不是一个好习惯。相反,应该像这样发送到本地广播地址(即192.168.1.255)

为此我写了IpAddressProvider:

public static class IpProvider
{
    private static readonly Lazy<string> _localAddress;
    private static readonly Lazy<string> _broadcastAddress;
    static IpProvider()
    {
        _localAddress = new Lazy<string>(GetLocalAddress);
        _broadcastAddress = new Lazy<string>(GetBroadcastAddress);
    }
    public static string LocalAddress { get { return _localAddress.Value; } }
    public static string BroadcastAddress { get { return _broadcastAddress.Value; } }
    private static string GetLocalAddress()
    {
        var hostnames = NetworkInformation.GetHostNames();
        foreach (var hn in hostnames)
        {
            //IanaInterfaceType == 71 => Wifi
            //IanaInterfaceType == 6 => Ethernet (Emulator)
            if (hn.IPInformation != null &&
                (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
                 || hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
            {
                return hn.DisplayName;
            }
        }
        return IpAddress.Broadcast.Address;
    }
    private static string GetBroadcastAddress()
    {
        var parts = _localAddress.Value.Split(new[] { '.' }).Take(3);
        return string.Join(".", parts) + ".255";
    }
}

现在我一起使用它们来发送广播消息:

var gatewayAddress = new IpAddress(IpProvider.BroadcastAddress);
var udpClient = new UdpClient(gatewayAddress);
await udpClient.SendAsync(data);
Tuple<IpAddress, byte[]> message;
while (udpClient.TryGetIncomingMessage(out message))
{
    if (message.Item1.Address == IpProvider.LocalAddress)
    {
        continue;
    }
    HandleIncomingPacket(message);
}