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

2 回答 2

2

您应该在一段时间内或其他循环中调用接收。

于 2011-08-12T15:22:50.153 回答
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);
}
于 2011-08-15T16:02:21.830 回答