首页 文章

c#udp无法接收

提问于
浏览
0

我已经在互联网上搜索了一两个星期,现在找到一个可以同时发送和接收的UDP客户端程序,但c#的这个主题没有任何内容 . 在过去的几天里,我尝试使用接收的线程创建UDP客户端 .

发送UDP数据包效果很好,但程序无法接收我发送到的服务器,我相信服务器正在将所有数据包发送到不同的端口 .

我该如何修复这个程序?

是否有更简单的方法来执行UDP编程,如StreamReader和StreamWriter for TCP?

static void CONNECTudp()
    {
        Console.WriteLine("Host:");
        IPAddress ipAddress = Dns.Resolve(Console.ReadLine()).AddressList[0];
        Console.WriteLine("Port:");
        int Port = int.Parse(Console.ReadLine());
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Port);
        Thread UDPthread = new Thread(() => CONNECTudpthread(ipEndPoint));
        UDPthread.Start();
        UdpClient udp = new UdpClient();
        do
        {
            Byte[] sendBytes = Encoding.ASCII.GetBytes(Console.ReadLine());
            udp.Send(sendBytes, sendBytes.Length, ipEndPoint);
        } while (true);
    }

    static void CONNECTudpthread(IPEndPoint ipEndPoint)
    {
        UdpClient udp = new UdpClient();
        do
        {
            try
            {
                Byte[] receiveBytes = udp.Receive(ref ipEndPoint);

                string returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine(returnData);
            }
            catch (Exception)
            {
            }
        } while (true);
    }

1 回答

  • 1

    由于UDP是面向消息的而不是面向流的,因此使用StreamReader和StreamWriter并不是真正的实用方法 . 在示例中坚持使用面向消息的I / O是最好的 .

    您的代码中的问题是您使用两个不同的 UdpClient 实例进行发送和接收 . 你也不能保证这是正确的 . 但如果是,那么如果你修改你的代码更像下面的代码,它应该工作:

    static void CONNECTudp()
    {
        Console.WriteLine("Host:");
        IPAddress ipAddress = Dns.Resolve(Console.ReadLine()).AddressList[0];
        Console.WriteLine("Port:");
        int Port = int.Parse(Console.ReadLine());
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Port);
    
        // Bind port immediately
        UdpClient udp = new UdpClient(0);
    
        // Pass UdpClient instance to the thread
        Thread UDPthread = new Thread(() => CONNECTudpthread(udp));
        UDPthread.Start();
        do
        {
            Byte[] sendBytes = Encoding.ASCII.GetBytes(Console.ReadLine());
            udp.Send(sendBytes, sendBytes.Length, ipEndPoint);
        } while (true);
    }
    
    static void CONNECTudpthread(UdpClient udp)
    {
        do
        {
            try
            {
                // Though it's a "ref", the "remoteEP" argument is really just
                // for returning the address of the sender.
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
                Byte[] receiveBytes = udp.Receive(ref ipEndPoint);
    
                string returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine(returnData);
            }
            catch (Exception)
            {
            }
        } while (true);
    }
    

相关问题