簡體   English   中英

Visual Studio 接收以太網 UDP (C#)

[英]Visual Studio Receiving Ethernet UDP (C#)

我正在嘗試通過以太網(從控制器)接收 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);
        } 
    }

此代碼應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM