Reputation: 7560
I've setup a very simple UdpClient to receive 8 bytes of data as fast as possible. The client is sending the data very fast but the server is receiving it in very choppy intervals of about 0.5 seconds. It stops on receive and then suddenly receives about ten datagrams in a row very fast, then stops again for ~0.5 seconds and so on. What could be the problem here? Ive tried turning off the firewall but it didnt help...
Client:
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
This code is continuously sending an accumulated buffer:
if (!_sending)
{
_sending = true;
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += (s2, e2) => { _sending = false; };
args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.100"), 14123);
args.SetBuffer(buffer, 0, buffer.Length);
_socket.SendToAsync(args);
}
Server:
UdpClient udp = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.0.100"), 14123));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] buffer = udp.Receive(ref endpoint);
int x = BitConverter.ToInt32(buffer, 0);
int y = BitConverter.ToInt32(buffer, 4);
Console.WriteLine(string.Format("Receiving x={0}, y={1} @ {2}", x, y, DateTime.Now.Ticks));
}
I know its very primitive code right now but its at least not throwing any exceptions...
Ive checked with Wireshark but I not sure exactly what to look for. The UDP messages get sent alright, without hiccups.
Ive read its a good idea to throttle UDP and not send as fast as possible. I did try that without any noticable difference. The sending is slower but the receiving is as chunky/bursty as before.
Both client and receiver is on the same dev-machine (Windows 7).
Here's some output from measuring the time (s) between Receive-calls. As you can see it get stuck for one second about every 30 iterations:
1,0180582
0,001
0
0
0,0010001
0
0
0
0
0,0010001
0
0
0
0
0
0
0
0
0
0
0,0010001
0
0
0
0
0
0,0010001
1,0170582
etc
Update
It looks like the delay arise after the buffers has been sent. The sending code seem to send the buffers very rapidly/fluidly, but when they appear in Wireshark they have a 1 second delay about every second of udp-firing. The receiving code doesnt seem to be casuing this delay, it is allready there. I dont get it.
Upvotes: 0
Views: 1110
Reputation: 84151
Seems to me that by using .Net asynchronous I/O you are giving away control of the send timing. I don't know what sort of delays are built into this async facility, but my guess is that some background thread pool is involved and those threads are polling some input queue.
I'd try to avoid all that overhead and just deal with sending in the same thread. UDP is very simple, just send and forget, especially when dealing with a single socket. I don't think async I/O overhead is needed here.
Upvotes: 1