Author Topic: [C#] Simple UDP Server - SysLog example  (Read 2957 times)

0 Members and 1 Guest are viewing this topic.

Offline xor

  • Peasant
  • *
  • Posts: 59
  • Cookies: 32
    • View Profile
[C#] Simple UDP Server - SysLog example
« on: May 06, 2015, 04:07:53 am »

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.

Code: [Select]

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

Offline thorynsmit

  • NULL
  • Posts: 1
  • Cookies: 0
    • View Profile
Re: [C#] Simple UDP Server - SysLog example
« Reply #1 on: July 27, 2015, 07:34:07 pm »
Nice could be useful


Sent from my iPhone using Tapatalk