[英]C# udp server not reading fast enough
public class RCon
{
static readonly ConcurrentQueue<byte[]> ReceivedPacketQueue = new ConcurrentQueue<byte[]>();
static IPEndPoint _ipEndPoint = new IPEndPoint(IPAddress.Parse("10.XXX.XX.117"), 2222);
static void Main(string[] args)
{
var client = new UdpClient
{
ExclusiveAddressUse = false,
Client = { ReceiveBufferSize = 8192 }
};
client.Client.Bind(_ipEndPoint);
client.BeginReceive(OnUdpData, client);
var message = new byte[100];
int numberOfPackets ;
for (numberOfPackets = 0; numberOfPackets < 84; numberOfPackets++)
{
client.Send(message, message.Length, _ipEndPoint);
}
}
static void OnUdpData(IAsyncResult result)
{
var socket = result.AsyncState as UdpClient;
var message = socket.EndReceive(result, ref _ipEndPoint);
ReceivedPacketQueue.Enqueue(message);
socket.BeginReceive(OnUdpData, socket);
}
}
我編寫了一個簡單的程序,該程序發送100字節的數據包,並且與服務器在同一台計算機上異步接收數據包並存儲在隊列中。 直到收到83個數據包后,數據包才可以正常工作。一旦我開始將數據包數量增加到84個以上,接收到的數據包的速率就會下降。 據我了解,這是因為客戶端讀取傳入數據包的速度不夠快,並且由於緩沖區溢出而丟失了數據包。 有什么方法可以使服務器足夠快以接收快速傳入的數據包。
盡管所有數據包都到達了(WireShark),但也有類似的問題C#UDP數據包丟失。我認為我在回答建議的內容,但問題仍然存在。
好吧,它在服務器和客戶端的相同端口上使用相同的IP :)
我對您的代碼進行了測試。 我添加了2個static vars static int sendIter = 0; static int recvIter = 0;
並運行該應用程序。 它以sendIter = 84和recvIter = 0..2-3迭代退出
我認為發生這種情況是因為您開始在函數中進行異步操作(BeginReceive),然后立即開始for循環以發送msg。 在幕后,BeginReceive啟動了線程,但是由於有這個for循環,即使它准備好處理傳入的消息,也沒有機會將上下文切換到它自己-占用所有cpu時間。
然后我在client.Send之后立即添加了Thread.Sleep(1)(它將允許應用程序切換線程上下文),並且我得到了sendIter和recvIter相等
所以我認為如果有CPU時間,客戶端就足夠快了
class Program
{
static readonly ConcurrentQueue<byte[]> ReceivedPacketQueue = new ConcurrentQueue<byte[]>();
static IPEndPoint _ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.4.142"), 2222);
static int sendIter = 0;
static int recvIter = 0;
static void Main(string[] args)
{
var client = new UdpClient
{
ExclusiveAddressUse = false,
Client = { ReceiveBufferSize = 8192 }
};
client.Client.Bind(_ipEndPoint);
client.BeginReceive(OnUdpData, client);
var message = new byte[100];
int numberOfPackets;
for (numberOfPackets = 0; numberOfPackets < 100; numberOfPackets++)
{
client.Send(message, message.Length, _ipEndPoint);
Thread.Sleep(1);
sendIter++;
}
Console.WriteLine(sendIter);
Console.WriteLine(recvIter);
Console.ReadKey();
}
static void OnUdpData(IAsyncResult result)
{
var socket = result.AsyncState as UdpClient;
var message = socket.EndReceive(result, ref _ipEndPoint);
ReceivedPacketQueue.Enqueue(message);
recvIter++;
socket.BeginReceive(OnUdpData, socket);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.