.NET 中的 UDP 发送/接收

发布于 2024-11-29 10:25:19 字数 1358 浏览 0 评论 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();
}

I'm new to UDP. Using a test environment, I am able to send/receive a single UDP message. However, I’m trying to figure out how to receive multiple UDP messages. I'd like MyListener service to receive UDP packets all day long, whenever I send them. I appreciate any help.

PS - As noted below in an answer, if I put a while(true) around my DoSomethingWithThisText, that will work while debugging. However, it won't work when trying to run MyListener as a service, because Start will never get past the while(true) loop.

My listener service looks like this...

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

My sender looks like this:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能怎样 2024-12-06 10:25:19

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

You should call the receive from within a while or some other loop.

日久见人心 2024-12-06 10:25:19

我最终使用了微软的异步方法,在这里找到 - BeginReceive结束接收

正如 Microsoft 建议的那样,我在 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);
}

I ended up using Microsoft's asynchronous methods, found here - BeginReceive and EndReceive .

Like Microsoft suggests, I call BeginReceive within my Start method like this:

UdpState s = new UdpState();
s.e = listenerEP;
s.u = udpListener;

udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s);

However, to get the listener to continue receiving messages, I call BeginReceive AGAIN within the ReceiveCallback function, recursively. This, of course, is a potential memory leak, but I've yet to encounter problems in my regression testing.

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文