How can I create a UDP Socket which receives data in local endpoint (I do not know the remote port where the data come from) in a non-blocking way?
I use .NET Core in Linux and I thought I could use ReceiveAsync() but it seems to not work this way.
I solved this, this way:
static void Main()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
socket.Bind(localEP);
while( my_condition){
Receive();}
}
private bool Receive()
{
received = false;
if (socket != null)
{
SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
ae.SetBuffer(recvBuffer, 0, recvBuffer.Length);
// callback
EventHandler<SocketAsyncEventArgs> rcb = new EventHandler<SocketAsyncEventArgs>(ReceiveCallback);
ae.Completed += rcb;
socket.ReceiveAsync(ae);
int counter = 0;
int recv_timeout = 500;
// create a delay waiting for data
while (!received && counter <= recv_timeout)
{
double nanosecs = recv_timeout * 1000;
long nanosperTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
int ticks = (int)(nanosecs / nanosperTick);
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedTicks < ticks) { }
sw.Stop();
counter++;
}
ae.Completed -= rcb;
ae.Dispose();
}
return received;
}
private void ReceiveCallback(object sender, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
if (e.BytesTransferred == Number_of_bytes_I_wait_for)
{
//get e.Buffer !
}
else
Console.WriteLine("??? number_of_bytes received: " + e.BytesTransferred);
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With