C#: UdpClient not sending data when calling close() to soon
On some computers I have the strange effect that UdpClient will not send data when UdpClient.Close() is called too soon after a UdpClient.Send(). I'm using .NET 4.0 and WireShark to verify the packet-loss.
The essential part of the coding is:
UdpClient sender = new UdpClient();
sender.Connect( new IPEndPoint( this.ipAddress, this.Port ) );
int bytesSent = sender.Send( data, data.Length );
sender.Close();
Weired is:
- On most Computers data will be sent without problems
- There is no exception or other error even if no packet was sent
- bytesSent will always equal data.Length
- On computers not sending packets a Thread.Sleep( 250 ) right before calling sender.Close() will fix the problem!
So, what could cancel the sending of packets, even after UdpClient.Send() reported the correct amount of bytes? Why is this manifesting only on certain machines? Could this be a different behaviour of some network drivers, anti-virus software or the like?
I also tried to set LingerOptions explicitly which should be unneccessary as the default is to send all pending data before closing the underlying socket. However, when doing a sender.Client.LingerState = new LingerOption( true, 10 ) (as descibed in http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.lingerstate.aspx) I get
SocketException (0x80004005): An unknown, invalid, or unsupported option
开发者_运维百科 or level was specified in a getsockopt or setsockopt call.
Any ideas what's going on?
Regards, Seven
OK, this has nothing to do with .NET and my software either. It seems that the virus scanner also scans the complete network trafic. And so .NET library functions for sending UDP packages actially did send the package, but the scanner discards it if UdpClient.Close() was called too soon after the Send() method.
So, there are two possible work-arounds now (that worked for me)
- Introduce a little sleep before calling UdpClient.Close() (about 4ms are sufficient)
- Remove the virus scanner and try another one (Microsoft Security Essentials does not show this effect)
精彩评论