Grupo de multidifusión UDP en Windows Phone 8

OK, esta es una que he estado tratando de averiguar por unos días ahora. Tenemos una aplicación en Windows Phone 7 donde los teléfonos se unen a un grupo de multidifusión y luego envían y reciben mensajes al grupo para hablar entre ellos. Nota: esta es la comunicación de teléfono a teléfono.

Ahora estoy tratando de migrar esta aplicación a Windows Phone 8, usando la función "Convertir a teléfono 8" en Visual Studio 2012, hasta ahora todo bien. Hasta que intento probar la comunicación de teléfono a teléfono. Los teléfonos parecen unirse a la multa del grupo y envían los datagramas OK. Incluso reciben los mensajes que envían al grupo; sin embargo, ningún teléfono recibe un mensaje de otro teléfono.

Aquí está el código de ejemplo detrás de mi página:

// Constructor
public MainPage()
{
    InitializeComponent();
}

// The address of the multicast group to join.
// Must be in the range from 224.0.0.0 to 239.255.255.255
private const string GROUP_ADDRESS = "224.0.1.1";

// The port over which to communicate to the multicast group
private const int GROUP_PORT = 55562;

// A client receiver for multicast traffic from any source
UdpAnySourceMulticastClient _client = null;

// Buffer for incoming data
private byte[] _receiveBuffer;

// Maximum size of a message in this communication
private const int MAX_MESSAGE_SIZE = 512;

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    _client = new UdpAnySourceMulticastClient(IPAddress.Parse(GROUP_ADDRESS), GROUP_PORT);
    _receiveBuffer = new byte[MAX_MESSAGE_SIZE];

    _client.BeginJoinGroup(
        result =>
        {
            _client.EndJoinGroup(result);
            _client.MulticastLoopback = true;
            Receive();
        }, null);
}

private void SendRequest(string s)
{
    if (string.IsNullOrWhiteSpace(s)) return;

    byte[] requestData = Encoding.UTF8.GetBytes(s);

    _client.BeginSendToGroup(requestData, 0, requestData.Length,
        result =>
        {
            _client.EndSendToGroup(result);
            Receive();
        }, null);
}

private void Receive()
{
    Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);
    _client.BeginReceiveFromGroup(_receiveBuffer, 0, _receiveBuffer.Length,
        result =>
        {
            IPEndPoint source;

            _client.EndReceiveFromGroup(result, out source);

            string dataReceived = Encoding.UTF8.GetString(_receiveBuffer, 0, _receiveBuffer.Length);

            string message = String.Format("[{0}]: {1}", source.Address.ToString(), dataReceived);
            Log(message, false);

            Receive();
        }, null);
}

private void Log(string message, bool isOutgoing)
{
    if (string.IsNullOrWhiteSpace(message.Trim('\0')))
    {
        return;
    }

    // Always make sure to do this on the UI thread.
    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        string direction = (isOutgoing) ? ">> " : "<< ";
        string timestamp = DateTime.Now.ToString("HH:mm:ss");
        message = timestamp + direction + message;
        lbLog.Items.Add(message);

        // Make sure that the item we added is visible to the user.
        lbLog.ScrollIntoView(message);
    });

}

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    // Don't send empty messages.
    if (!String.IsNullOrWhiteSpace(txtInput.Text))
    {
        //Send(txtInput.Text);
        SendRequest(txtInput.Text);
    }
}

private void btnStart_Click(object sender, RoutedEventArgs e)
{
    SendRequest("start now");
}

Para simplemente probar la pila UDP, descargué la muestra de MSDN encontradaaquí y probé esto en un par de dispositivos con Windows Phone 7 y funciona como se esperaba. Luego me convertí a Windows Phone 8 y lo implementé en mis teléfonos, nuevamente, los dispositivos parecen iniciar su conexión y el usuario puede ingresar su nombre. Sin embargo, nuevamente los dispositivos no pueden ver o comunicarse con otros dispositivos.

Finalmente, implementé una prueba de comunicación simple utilizando la nueva implementación de DatagramSocket, y nuevamente veo una iniciación exitosa, pero no una comunicación entre dispositivos.

Este es el mismo código detrás de la página que usa la implementación del datagrama:

// Constructor
public MainPage()
{
    InitializeComponent();
}

// The address of the multicast group to join.
// Must be in the range from 224.0.0.0 to 239.255.255.255
private const string GROUP_ADDRESS = "224.0.1.1";

// The port over which to communicate to the multicast group
private const int GROUP_PORT = 55562;

private DatagramSocket socket = null;

private void Log(string message, bool isOutgoing)
{
    if (string.IsNullOrWhiteSpace(message.Trim('\0')))
        return;

    // Always make sure to do this on the UI thread.
    Deployment.Current.Dispatcher.BeginInvoke(
    () =>
    {
        string direction = (isOutgoing) ? ">> " : "<< ";
        string timestamp = DateTime.Now.ToString("HH:mm:ss");
        message = timestamp + direction + message;
        lbLog.Items.Add(message);

        // Make sure that the item we added is visible to the user.
        lbLog.ScrollIntoView(message);
    });
}

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    // Don't send empty messages.
    if (!String.IsNullOrWhiteSpace(txtInput.Text))
    {
        //Send(txtInput.Text);
        SendSocketRequest(txtInput.Text);
    }
}

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    socket = new DatagramSocket();
    socket.MessageReceived += socket_MessageReceived;

    try
    {
        // Connect to the server (in our case the listener we created in previous step).
        await socket.BindServiceNameAsync(GROUP_PORT.ToString());
        socket.JoinMulticastGroup(new Windows.Networking.HostName(GROUP_ADDRESS));
        System.Diagnostics.Debug.WriteLine(socket.ToString());
    }
    catch (Exception exception)
    {
        throw;
    }
}

private async void SendSocketRequest(string message)
{
    // Create a DataWriter if we did not create one yet. Otherwise use one that is already cached.
    //DataWriter writer;
    var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(GROUP_ADDRESS), GROUP_PORT.ToString());
    //writer = new DataWriter(socket.OutputStream);
    DataWriter writer = new DataWriter(stream);

    // Write first the length of the string as UINT32 value followed up by the string. Writing data to the writer will just store data in memory.
   // stream.WriteAsync(
    writer.WriteString(message);

    // Write the locally buffered data to the network.
    try
    {
        await writer.StoreAsync();
        Log(message, true);
        System.Diagnostics.Debug.WriteLine(socket.ToString());
    }
    catch (Exception exception)
    {
        throw;
    }
    finally
    {
        writer.Dispose();
    }
}

void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
    try
    {
        uint stringLength = args.GetDataReader().UnconsumedBufferLength;
        string msg = args.GetDataReader().ReadString(stringLength);

        Log(msg, false);
    }
    catch (Exception exception)
    {
        throw;
    }
}

Anoche me llevé los teléfonos a casa para probarlos en la red inalámbrica de mi hogar, baja y he recibido una comunicación exitosa con el dispositivo.

Para resumir, mi código heredado de Windows Phone 7 funciona bien en mi red de trabajo. El puerto a Windows Phone 8 (sin cambio de código real) no envía comunicación entre dispositivos. Este código funciona en mi red doméstica. El código se ejecuta con el depurador adjunto y no hay signos de errores o excepciones en ningún lugar durante la ejecución.

Los teléfonos que estoy usando son:

Windows Phone 7 - Nokia Lumia 900 (* 2), Nokia Lumia 800 (* 3) Windows Phone 8 - Nokia Lumia 920 (* 1), Nokia Limia 820 (* 2)

Todos ellos están ejecutando el último sistema operativo, y están en modo desarrollador. El entorno de desarrollo es Windows 8 Enterprise ejecutando Visual Studio 2012 Professional.

No puedo decirle mucho sobre el trabajo de la red inalámbrica, aparte de que los dispositivos Phone 7 no tienen problemas.

En cuanto a la red inalámbrica doméstica que utilicé, eso es solo un enrutador básico de banda ancha de BT sin que se modifique ninguna de las configuraciones "listas para usar".

Claramente hay un problema con la forma en que se configuran las dos redes, pero también hay un problema muy claro con la forma en que Windows Phone 8 implementa los mensajes UDP.

Cualquier entrada sería apreciada ya que esto me está volviendo loco en este momento.

Respuestas a la pregunta(3)

Su respuesta a la pregunta