在.NET中发送和接收UDP数据包 [英] Sending and receiving UDP packets in .NET

查看:106
本文介绍了在.NET中发送和接收UDP数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在LAN上测试UDP通信.我只有一小段代码,并且尝试在两台计算机上运行它(一台应等待接收,另一台应发送).奇怪的是,计算机A发送并且B正确接收,但是如果我尝试A接收而B发送则无法正常工作.你知道为什么会这样吗?

I am trying to test UDP communications on a LAN. I have a small piece of code to and I have tried to run it in 2 computers (one should wait to receive and the other one should send). The strange thing is that computer A sends and B receives properly but if I try A to receive and B to send it does not work. Do you know why could it be?

public void SendBroadcast(int port, string message)
    {
        UdpClient client = new UdpClient();
        byte[] packet = Encoding.ASCII.GetBytes(message);

        try
        {
            client.Send(packet, packet.Length, IPAddress.Broadcast.ToString(), port);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

public void Receive(int port)
    {
        UdpClient client = null;

        try
        {
            client = new UdpClient(port);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);


        while (true) 
        {
            try
            {
                byte[] packet = client.Receive(ref server);
                Console.WriteLine("{0}, {1}", server, Encoding.ASCII.GetString(packet));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

通话:

  SendBroadcast(444, "hello"); Receive(444);

如果我在同一台计算机上运行该程序的2个实例,则它可以正常运行,但每次调用都会创建3个程序包.

If I run 2 instances of the program on the same computer it works properly but creates 3 packages per call.

提前谢谢.

推荐答案

好吧,如果相同的代码可以在一个代码上运行而不能在另一个代码上运行,那就是您的环境.检查您的防火墙设置,确保它没有阻止发送方广播或阻止接收方接收. Wireshark(甚至Windows的netmon)在这里应该会有所帮助.

Well, if the same code works on one and not the other, it's your environment. Check your firewall settings, make sure it's not preventing the broadcast on the sender or preventing receipt on the receiver. Wireshark (or even Windows' netmon) should be helpful here.

这篇关于在.NET中发送和接收UDP数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆