我通常是 Sockets 和 C# 的新手,并且很难实现一个简单的 upd 侦听器函数。我花了很多时间在网上搜索,但未能成功地整合在线众多示例中的任何一个。因此,任何建议、链接、示例将不胜感激!
此时,我有一个第三方应用程序通过端口 6600 广播一条通用 UPD 消息,其中包含有关应用程序服务器位置(服务器名称、IP 地址等)的信息。我想设计我的侦听器客户端应用程序来捕获 UPD 广播并生成可用于将来处理的可用服务器的集合。
我遇到的问题是,当我尝试使用 listener.Listen(0) 创建侦听器时,如果失败并生成一般类型错误。如果我尝试使用 UdpClient 类,我的应用程序将挂起并且永远不会返回任何数据。下面列出了这两个示例的代码:
namespace UDPListener
{
class Program
{
static void Main(string[] args)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
listener.Bind(new IPEndPoint(IPAddress.Any, 6600));
listener.Listen(6);
Socket socket = listener.Accept();
Stream netStream = new NetworkStream(socket);
StreamReader reader = new StreamReader(netStream);
string result = reader.ReadToEnd();
Console.WriteLine(result);
socket.Close();
listener.Close();
}
}
}
和 UdpClient:
private void IdentifyServer()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(6600);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Output.Text = ("This is the message you received " +
returnData.ToString());
Output.Text = ("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}