接收对UDP广播C#的答复

问题描述

| 我正在尝试发送udp广播,并使用c#接收答案。虽然发送广播的效果很好,但是我在C#中没有收到任何答案。但是当我看一下wireshark时,我可以看到已经发送了一个答案: 从192.168.0.141发送到192.168.0.255 从192.168.0.105发送到255.255.255.255(这就是答案) Wireshark日志:
1   0.000000    192.168.0.141   192.168.0.255   UDP Source port: 55487  Destination port: 17784
2   0.000851    192.168.0.105   255.255.255.255 UDP Source port: 17784  Destination port: 55487
那就是我的C#代码
    private static byte[] SendBuffer = new byte[] { 1,2,3 };

    public static void SendAndReceivebroadcast( byte[] data,IPEndPoint broadcastEndpoint )
    {

        using( Socket broadcastSocket = new Socket( AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp ) )
        {
            broadcastSocket.SetSocketoption( SocketoptionLevel.socket,SocketoptionName.broadcast,1 );
            broadcastSocket.SendTo( data,broadcastEndpoint );
            receivePort = broadcastSocket.LocalEndPoint.ToString().Split( \':\' )[1];
            Console.WriteLine( \"Sent {0} from Port {1}\",CollectionsHelper.ItemsToString( data,\"{0:X2}\" ),broadcastSocket.LocalEndPoint.ToString() );
            broadcastSocket.Close();
        }

        using( Socket receiveSocket = new Socket( AddressFamily.InterNetwork,ProtocolType.Udp ) )
        {
            IPEndPoint broadcastAddress = new IPEndPoint( IPAddress.Any,Convert.ToInt32( receivePort ) );
            UdpClient udpClient = new UdpClient();
            udpClient.Client.SetSocketoption( SocketoptionLevel.socket,SocketoptionName.ReuseAddress,true );
            udpClient.Client.Bind( broadcastAddress );
            IPEndPoint remoteIP = new IPEndPoint( IPAddress.Any,Convert.ToInt32( receivePort ) );
            byte[] answer = udpClient.Receive( ref remoteIP );
        }
    }
调用udpClient.Receive时程序停止。有人可以帮我吗? :)     

解决方法

         您应该使用
ReceiveFrom
Receive
表示TCP。 如果我没记错的话,广播消息不会排队。广播之前叫
BeginReceiveFrom
,之后叫
EndReceiveFrom
。     ,        由于您使用相同的发送和接收过程,因此需要在发送消息之前打开接收器,并且需要使用udpClient.ReceiveAsync()并等待答案,然后才能关闭程序。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...