Created
August 20, 2019 09:21
-
-
Save c6burns/65221871d73e3ee390d66e09844f2873 to your computer and use it in GitHub Desktop.
noblocking threaded UDP recv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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