【问题标题】:Visual Studio Receiving Ethernet UDP (C#)Visual Studio 接收以太网 UDP (C#)
【发布时间】:2020-03-30 21:21:43
【问题描述】:

我正在尝试通过以太网(从控制器)接收 UDP 数据并遇到了一些问题。我知道控制器正在发送数据,因为我可以在wireshark 上看到它通过,但我尝试过的所有事情都没有奏效。下面的代码是我发现能够接收我想要的数据的最接近的代码。 更多信息:控制器IP和端口是192.168.82.27:1743,我端接收IP和端口是192.168.82.21:1740

    public class UDPListener
    {
        static UdpClient client = new UdpClient(1740);
        public static void Main()
        {
            try
            {
                client.BeginReceive(new AsyncCallback(recv), null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            while (true)
            {

            }
        }
        //CallBack
        private static void recv(IAsyncResult res)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 1743);
            byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
            //Process code
            Console.WriteLine(RemoteIpEndPoint + "  :  " + Encoding.ASCII.GetString(received));
            client.BeginReceive(new AsyncCallback(recv), null);
        } 
    }

【问题讨论】:

    标签: c# visual-studio udp ethernet udpclient


    【解决方案1】:

    这段代码应该可以工作:

    public class Receiver
    {
        private readonly UdpClient udp;
        private IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1740);
        public Receiver()
        {
            udp = new UdpClient
            {
                ExclusiveAddressUse = false
            };
            udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udp.Client.Bind(ip);
        }
        public void StartListening()
        {
            udp.BeginReceive(Receive, new object());
        }
        private void Receive(IAsyncResult ar)
        {
            var bytes = udp.EndReceive(ar, ref ip);
            StartListening();
        }
    }
    

    【讨论】:

    • 感谢您的回复,但它给我的似乎比我发布的代码少?也许我做错了,但控制台没有给我任何东西(我在一节中添加了输出接收到的任何内容)。当我运行我最初发布的代码时,控制台输出如下内容: 192.168.82.247:1740 : ? @???这显然不是我正在寻找的数据,但它确实是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多