繁体   English   中英

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

[英]UDP Listener using sockets generating type error

我是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());
        }

dtb绝对是写的! 经过大量研究和朋友的帮助,我意识到我真正想要的是多播解决方案。 我将在下面提供链接。

@dtb,感谢您帮助我指出正确的方向!

http://www.codeproject.com/Articles/1705/IP-Multicasting-in-C

http://codeidol.com/csharp/csharp-network/IP-Multicasting/Csharp-IP-Multicast-Support/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM