首页 文章

UDP中的UDP发送/接收

提问于
浏览
0

我是UDP的新手 . 使用测试环境,我能够发送/接收单个UDP消息 . 但是,我正在试图弄清楚如何接收多个UDP消息 . 每当我发送它时,我都希望MyListener服务能够整天接收UDP数据包 . 我感谢任何帮助 .

PS - 如下面的答案中所述,如果我在我的DoSomethingWithThisText周围放置一段时间(true),那么在调试时它将起作用 . 但是,当尝试将MyListener作为服务运行时,它将无法工作,因为Start将永远不会超过while(true)循环 .

我的听众服务看起来像这样......

public class MyListener
{
    private udpClient udpListener;
    private int udpPort = 51551;

    public void Start()
    {
        udpListener = new UdpClient(udpPort);
        IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, udpPort);
        Byte[] message = udpListener.Receive(ref listenerEndPoint);

        Console.WriteLine(Encoding.UTF8.GetString(message));
        DoSomethingWithThisText(Encoding.UTF8.GetString(message));
    }
}

我的发件人看起来像这样:

static void Main(string[] args)
{
    IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
    int port = 51551;

    //define some variables.

    Console.Read();
    UdpClient client = new UdpClient();
    client.Connect(new System.Net.IPEndPoint(ipAddress, port));
    Byte[] message = Encoding.UTF8.GetBytes(string.Format("var1={0}&var2={1}&var3={2}", new string[] { v1, v2, v3 }));
    client.Send(message, message.Length);
    client.Close();
    Console.WriteLine(string.Format("Sent message");
    Console.Read();
}

2 回答

  • 2

    你应该在一段时间或其他一些循环中调用receive .

  • 1

    我最终使用了Microsoft的异步方法,在这里找到 - BeginReceiveEndReceive .

    像微软建议的那样,我在我的Start方法中调用BeginReceive,如下所示:

    UdpState s = new UdpState();
    s.e = listenerEP;
    s.u = udpListener;
    
    udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s);
    

    但是,为了让侦听器继续接收消息,我在递归中调用ReceiveCallback函数中的BeginReceive AGAIN . 当然,这是一个潜在的内存泄漏,但我还没有在回归测试中遇到问题 .

    private void ReceiveCallback(IAsyncResult ar)
    {
        UdpClient u = (UdpClient)((UdpState)ar.AsyncState).u;
        IPEndPoint e = (IPEndPoint)((UdpState)ar.AsyncState).e;
    
        UdpState s = new UdpState();
        s.e = e;
        s.u = u;
        udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s); 
    
        Byte[] messageBytes = u.EndReceive(ar, ref e);
        string messageString = Encoding.ASCII.GetString(messageBytes);
    
        DoSomethingWithThisText(messageString);
    }
    

相关问题