Domanda

Sto provando a inviare una trasmissione e quindi lasciare che il server risponda:

public static void SendBroadcast()
    {
        byte[] buffer = new byte[1024];
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

        socket.Connect(new IPEndPoint(IPAddress.Broadcast, 16789));
        socket.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Anyone out there?"));

        var ep = socket.LocalEndPoint;

        socket.Close();

        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        socket.Bind(ep);
        socket.Receive(buffer);
        var data = UTF8Encoding.UTF8.GetString(buffer);
        Console.WriteLine("Got reply: " + data);

        socket.Close();
    }

    public static void ReceiveBroadcast()
    {
        byte[] buffer = new byte[1024];

        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        var iep = new IPEndPoint(IPAddress.Any, 16789);
        socket.Bind(iep);

        var ep = iep as EndPoint;
        socket.ReceiveFrom(buffer, ref ep);
        var data = Encoding.UTF8.GetString(buffer);

        Console.WriteLine("Received broadcast: " + data + " from: " + ep.ToString());

        buffer = UTF8Encoding.UTF8.GetBytes("Yeah me!");
        socket.SendTo(buffer, ep);

        socket.Close();
    }

La trasmissione arriva bene, ma la risposta no.Non viene generata alcuna eccezione.Qualcuno può aiutarmi?Devo aprire una nuova connessione per la risposta o qualcosa del genere?

MODIFICARE:Ho cambiato un po' il mio codice e ora funziona!Grazie per la tua risposta!

È stato utile?

Soluzione

Non sembra il tuo SendBroadcast() socket è legato a una porta quindi non riceverà nulla.In effetti il ​​tuo ReceiveBroadcast() socket sta inviando la risposta alla propria porta, quindi riceverà la propria risposta.

ReceiveBroadcast: binds to port 16789
SendBroadcast:    sends to port 16789
ReceiveBroadcast: receives datagram on port 16789
ReceiveBroadcast: sends reply to 16789
ReceiveBroadcast: **would receive own datagram if SendTo follwed by Receive**

Devi (a) avere SendBroadcast() legarsi ad a diverso porto e cambio ReceiveBroadcast() inviare a quella porta (invece che al proprio endpoint ep), oppure (b) fare in modo che entrambe le funzioni utilizzino lo stesso oggetto socket in modo che possano Entrambi ricevere datagrammi sulla porta 16789.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top