C#UDP套接字:从一个特定端口发送/接收到另一个指定端口

时间:2014-09-30 17:16:03

标签: c# sockets udp udpclient

我有一个嵌入式系统,我想在C#上使用UDP发送和接收信息。我无法使我的程序接收完全有效的UDP数据包。

嵌入式系统等待端口57301的UDP数据包,从端口57301(不是任意一个!)发送,然后从端口57311应答端口57311.Wireshark向我显示从计算机到嵌入式系统和嵌入式系统的完全有效数据包到电脑,但C#程序不想看到它。

    // Button handler, I press it to send message
    private void SendUDP_Click(object sender, EventArgs e)
    {
        Send();

    }

    // Button handler, I press it before sending anything just to start receiver
    private void button1_Click(object sender, EventArgs e)
    {
        StartReceive();
    }

    // Sending completely as planned
    void Send()
    {
        UdpClient udp = new UdpClient(57301);
        byte[] message = Encoding.Default.GetBytes(Message.Text);

        IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.0.14"), 57301);
        udp.Send(message, message.Length, ep);
        udp.Close();
    }

    void StartReceive()
    {
        ThreadStart tstart = new ThreadStart(Receive);
        workReceive = new Thread(tstart);
        workReceive.Start();
    }


    bool stopReceive = false;
    Thread workReceive = null;
    UdpClient udp = null;

    void Receive()
    {
        ShowMessage("Receive started");
        try
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 57311);
            udp = new UdpClient(ep);

            while (true)
            {
                IPEndPoint remote = null;
                byte[] message = udp.Receive(ref remote);   // <--- NEVER RECEIVE ANYTHING!
                ShowMessage("Received!");

                if (stopReceive == true) break;
            }
        }
        catch (Exception e)
        {
            ShowMessage("Exception!");
        }
        finally
        {
            if (udp != null) udp.Close();
        }
    }

问题所在的任何建议?

UPD:问题在于嵌入式系统:错误的UDP校验和计算例程 - 不知道为什么我认为它应该与ip4例程相同。

0 个答案:

没有答案