Skip to content

Instantly share code, notes, and snippets.

@c6burns
Created August 20, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c6burns/65221871d73e3ee390d66e09844f2873 to your computer and use it in GitHub Desktop.
Save c6burns/65221871d73e3ee390d66e09844f2873 to your computer and use it in GitHub Desktop.
noblocking threaded UDP recv
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
namespace UDPClientPlayground
{
class Program
{
const int recvTimeout = 500;
public static volatile bool cease = false;
static Thread pumpThread;
static UdpClient udpClient;
static void Main(string[] args)
{
Console.WriteLine("UDP Test application");
pumpThread = new Thread(PumpThread);
pumpThread.Start();
Console.ReadKey();
cease = true;
pumpThread.Join();
Console.WriteLine("Application quit");
}
static void PumpThread()
{
using (udpClient = new UdpClient("127.0.0.1", 9050))
{
udpClient.Client.Blocking = false;
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 9050);
byte[] recvData = null;
while (!cease)
{
int recvBytes = UdpClientTryRecv(udpClient, ref recvData, ref ep, recvTimeout);
if (recvBytes < 0)
{
break;
}
if (recvBytes > 0)
{
Console.WriteLine("Recv: {0} bytes", recvBytes);
}
}
}
}
static int UdpClientTryRecv(UdpClient udpClient, ref byte[] dataInput, ref IPEndPoint ep, int timeoutMS = 0)
{
Stopwatch sw = Stopwatch.StartNew();
do
{
try
{
dataInput = udpClient.Receive(ref ep);
if (dataInput != null) return dataInput.Length;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.WouldBlock)
{
Console.WriteLine("Except occurred during rec: {0}", ex.Message);
return -1;
}
}
} while (sw.ElapsedMilliseconds < timeoutMS);
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment