我试图发送一个广播,然后让服务器回复到它:

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();
    }

广播到达细,但回复并不能。没有抛出异常。谁能帮我?我一定要打开的答复什么新的连接?

编辑:我的代码更改了一下,现在它的作品!感谢您的答复!

有帮助吗?

解决方案

它看起来并不像那么他不会接受任何您SendBroadcast()套接字绑定到一个端口。其实你ReceiveBroadcast()插座发送回复回自己的端口,这样他将获得自己的答复。

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**

您需要(一)已SendBroadcast()绑定到的不同的的端口,并更改ReceiveBroadcast()发送到端口(而不是他自己的端点ep),或(b)有两个功能使用同一个插座对象,这样他们可以两个在端口16789接收的数据报。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top