gpt4 book ai didi

c# - 本地主机UDP丢包率高的原因?

转载 作者:太空狗 更新时间:2023-10-29 20:39:39 24 4
gpt4 key购买 nike

在我的 WPF 4.0 应用程序中,我实现了一个 UDP 监听器,如下所示。在我的 Windows 7 PC 上,我在 localhost 上同时运行服务器和客户端。

每个接收到的数据报都是一个较大位图的扫描线,因此在接收到所有扫描线后,位图将显示在 UI 线程上。这似乎有效。然而,偶尔会丢失 1-50% 的扫描线。我希望它在弱网络连接上运行,但在本地运行时不会。

UDP下面这段代码可能会导致丢包的原因是什么?

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT);
udpClient = new UdpClient(endPoint);
udpClient.Client.ReceiveBufferSize = 65535; // I've tried many different sizes...

var status = new UdpStatus()
{
u = udpClient,
e = endPoint
};

udpClient.BeginReceive(new AsyncCallback(UdpCallback), status);

private void UdpCallback(IAsyncResult ar)
{
IPEndPoint endPoint = ((UdpStatus)(ar.AsyncState)).e;
UdpClient client = ((UdpStatus)(ar.AsyncState)).u;

byte[] datagram = client.EndReceive(ar, ref endPoint);

// Immediately begin listening for next packet so as to not miss any.
client.BeginReceive(new AsyncCallback(UdpCallback), ar.AsyncState);

lock (bufferLock)
{
// Fast processing of datagram.
// This merely involves copying the datagram (scanline) into a larger buffer.
//
// WHEN READY:
// Here I can see that scanlines are missing in my larger buffer.
}
}

如果我在回调中放入 System.Diagnostics.Debug.WriteLine,包丢失会急剧增加。似乎此回调内部的小毫秒延迟会导致问题。尽管如此,在我的发布版本中还是出现了同样的问题。

更新

当我稍微强调 UI 时,错误会变得更频繁。 UdpClient 实例是否在主线程上执行?

最佳答案

为避免线程阻塞问题,请尝试使用较新的 IO 完成端口接收方法的这种方法:

private void OnReceive(object sender, SocketAsyncEventArgs e)
{
TOP:
if (e != null)
{
int length = e.BytesTransferred;
if (length > 0)
{
FireBytesReceivedFrom(Datagram, length, (IPEndPoint)e.RemoteEndPoint);
}
e.Dispose(); // could possibly reuse the args?
}
Socket s = Socket;
if (s != null && RemoteEndPoint != null)
{
e = new SocketAsyncEventArgs();
try
{
e.RemoteEndPoint = RemoteEndPoint;
e.SetBuffer(Datagram, 0, Datagram.Length); // don't allocate a new buffer every time
e.Completed += OnReceive;
// this uses the fast IO completion port stuff made available in .NET 3.5; it's supposedly better than the socket selector or the old Begin/End methods
if (!s.ReceiveFromAsync(e)) // returns synchronously if data is already there
goto TOP; // using GOTO to avoid overflowing the stack
}
catch (ObjectDisposedException)
{
// this is expected after a disconnect
e.Dispose();
Logger.Info("UDP Client Receive was disconnected.");
}
catch (Exception ex)
{
Logger.Error("Unexpected UDP Client Receive disconnect.", ex);
}
}
}

关于c# - 本地主机UDP丢包率高的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483836/

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