C# UDP socket app to listen to messages from vario

2019-08-28 10:59发布

问题:

I have a system monitor app that needs to listen to messages from various UDP sockets on another machine. The other sockets continuously send heartbeats to this given IP/port.

This exception gets thrown when calling BeginReceiveFrom: "A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied"

I shouldn't have to call connect because data is already getting sent to this ip endpoint. plus the data is coming from various sockets.

    private Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // bind socket
        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        m_localEndPoint = new IPEndPoint(ipAddress, 19018);
        m_socket.Bind(m_localEndPoint);

        m_socket.BeginReceiveFrom(m_data, 
                                  m_nBytes, 
                                  MAX_READ_SIZE, 
                                  SocketFlags.None,
                                  ref m_localEndPoint, 
                                  new AsyncCallback(OnReceive),
                                  null);

    }

    private void OnReceive(IAsyncResult ar)
    {
            int nRead = m_socket.EndReceiveFrom(ar, ref m_localEndPoint);
     }

回答1:

I was able to get the desired behavior with the UdpClient class.



回答2:

Your problem was you were binding to the IP assigned to you, you should bind to IP you want receive from - in your case:

m_socket.Bind(new IPEndPoint(IPAddress.Any, 12345));