gpt4 book ai didi

.net - 使用.Net Core创建UDP套接字

转载 作者:行者123 更新时间:2023-12-02 03:23:02 26 4
gpt4 key购买 nike

如何创建一个以非阻塞方式在本地端点(我不知道数据来自远程端口)接收数据的 UDP 套接字?

我在 Linux 中使用 .NET Core,我以为我可以使用 ReceiveAsync(),但它似乎无法以这种方式工作。

最佳答案

我这样解决了这个问题:

    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 - 使用.Net Core创建UDP套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com