Re: [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- From: "Peter Duniho" <no.peted.spam@xxxxxxxxxxxxxxxxxx>
- Date: Thu, 23 Jul 2009 11:07:09 -0700
On Thu, 23 Jul 2009 08:39:03 -0700, Andreas Huber <ahd6974-spamboostorgtrap@xxxxxxxxx> wrote:
The problem I have with this code is that the server receives my
message approximatively 1 time out of 10.
But if I remove the finally block (NetworkStream and TcpClient
closing), the server receives my message every time.
What am I doing wrong here?
I'm pretty sure I have to close my connection and I read in some doc
that the underlying NetworkStream should also be closed.
You might try the LingerOption property:
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.lingerstate.aspx
Unfortunately, at least according to the documentation, you can only _shorten_ the linger time for the socket using that property:
When the LingerTime property stored in the LingerState property
is set greater than the default IP protocol time-out, the default
IP protocol time-out will still apply and override.
I believe that the more general problem is that the original code is not calling Socket.Shutdown() before disposing/closing the stream and socket. I'm not an expert, but my recollection is that closing an open socket results in a "reset" of the connection (i.e. "RST" packet being sent) while a shutdown results in a "graceful closure" of the connection (i.e. "FIN" packet being sent). Some quick Googling seems to confirm this, with the additional wrinkle that the close initially causes a "FIN", but the network stack will send a "RST" if the other end tries to send any data.
So, it would be worthwhile to try a true graceful closure. Call Socket.Shutdown() after all the data is sent and then go ahead and wait for the full graceful closure, by reading from the socket until the end-of-stream is indicated (by a 0 byte read). As I understand it, that will ensure that both ends get a chance to read the data until they've both agree to close their sockets.
Pete
.
- Follow-Ups:
- Re: [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- From: Andreas Huber
- Re: [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- References:
- [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- From: Robert Lochon
- Re: [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- From: Andreas Huber
- [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- Prev by Date: Re: Accessing Win Mobile phone's Cell Tower info
- Next by Date: Re: How to copy a integer length in a array.
- Previous by thread: Re: Weird behaviour with Close method of TcpClient class
- Next by thread: Re: [C# .NET 2.0] Weird behaviour with Close method of TcpClient class
- Index(es):
Relevant Pages
|