How to implement a UDP listener in the background?

2019-06-09 16:53发布

I want to run this UDPListener in the background:

// launch this in a background thread
private static void UDPListen()
{
    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
    using( var udpClient = new UdpClient(10000)) 
    {
       while (true)
       {
           var buffer = udpClient.Receive(ref remoteEndPoint);
           var loggingEvent = System.Text.Encoding.Unicode.GetString(buffer);
           // ...
       }
    }
}

Can I put this inside a Task.Run() and run it in the while() loop?

1条回答
祖国的老花朵
2楼-- · 2019-06-09 17:15

This is how I set it up after a bit of reading and it works. Quite simple!

Asynchronous Method

    private static void UDPListener()
    {
        Task.Run(async () =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var receivedResults = await udpClient.ReceiveAsync();
                    loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
                }
            }
        });
    }

The appender in the log4net config file should be set up as something like:

</log4net>
    <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
        <remoteAddress value="127.0.0.1" />
        <remotePort value="11000" />
        <layout type="log4net.Layout.PatternLayout, log4net">
            <conversionPattern value="%-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
    </appender>

    <root>
        <appender-ref ref="UdpAppender" />

    </root>
</log4net>

Synchronous Method

As appose to the asynchronous method above, this can be also implemented in synchronous method in a very similar fashion:

    private static void UDPListener()
    {
        Task.Run(() =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    var receivedResults = udpClient.Receive(ref remoteEndPoint);
                    loggingEvent += Encoding.ASCII.GetString(receivedResults);
                }
            }
        });
    }
查看更多
登录 后发表回答