C# UDP 套接字应用程序来侦听来自各种套接字的消息 [英] C# UDP socket app to listen to messages from various sockets
问题描述
我有一个系统监视器应用程序,它需要监听来自另一台机器上各种 UDP 套接字的消息.其他套接字不断地向这个给定的 IP/端口发送心跳.
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.
调用 BeginReceiveFrom 时抛出此异常:由于套接字未连接并且(使用 sendto 调用在数据报套接字上发送时)未提供地址,因此不允许发送或接收数据的请求"
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"
我不应该调用 connect 因为数据已经发送到这个 ip 端点.加上数据来自各种套接字.
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);
}
推荐答案
我能够通过 UdpClient 类获得所需的行为.
I was able to get the desired behavior with the UdpClient class.
这篇关于C# UDP 套接字应用程序来侦听来自各种套接字的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!