使用 .Net Core 创建 UDP 套接字 [英] Create UDP socket with .Net Core
本文介绍了使用 .Net Core 创建 UDP 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个以非阻塞方式在本地端点(我不知道数据来自的远程端口)接收数据的 UDP 套接字?我在 Linux 中使用 .Net Core,我认为我可以使用 ReceiveAsync() 但它似乎不能这样工作.
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.
任何建议都可能有用.
推荐答案
我是这样解决的:
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;
}
}
这篇关于使用 .Net Core 创建 UDP 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文