The following is a console application that demonstrates a simple UDP Server designed to receive data only.
The program calls the static UdpListener method and passes in the port it wants to listen to.
You can call this method as many times as you like with different port numbers to create more listening sockets.
In the example below, I am listening to port 514 (SysLog) and simply dumping the received text to the console.
Press CTRL+C to set the _exiting flag.
* No error handling.
* No clean disposal of sockets or task cleanup.
* Quick and dirty exaple.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SysLog
{
class Program
{
private static ManualResetEvent _exiting = new ManualResetEvent(false);
static void Main(string[] args)
{
Console.CancelKeyPress += (sender, eventArgs) => _exiting.Set();
UdpListener(514);
_exiting.WaitOne();
}
private static void UdpListener(int port)
{
Task.Run(async () =>
{
using (var udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port)))
{
while (true)
{
var receivedResults = await udpClient.ReceiveAsync();
var s = String.Format("[{0}] {1}", receivedResults.RemoteEndPoint, Encoding.ASCII.GetString(receivedResults.Buffer));
Console.WriteLine(s);
}
}
});
}
}
}