首页 文章

UDP侦听器使用套接字生成类型错误

提问于
浏览
1

我是Socket和C#的新手,我很难实现一个简单的upd监听器函数 . 我花了很多时间在网上搜索并没有成功地在网上拦截任何数字的例子 . 所以任何建议,链接,例子将不胜感激!

此时,我有一个第三方应用程序通过端口6600广播一个通用UPD消息,其中包含有关应用程序服务器位置的信息(ServerName,IP Address等) . 我想设计我的侦听器客户端应用程序来捕获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());
        }

1 回答

相关问题