Create UDP socket with .Net Core
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;
}
}