473,659 Members | 3,395 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Close() timeout in NetworkStream and Socket?

I have an application that wants to open a Socket, write data and close the
socket. A persistent connection would be nice, but it's intended to
operate in an environment where the network connection probably isn't
reliable.

So I do this:

// open socket
m_networkSocket = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
IPEndPoint them = new IPEndPoint(IPAd dress.Parse(hos tname), port);
m_networkSocket .Connect(them);
m_networkConnec tion = new NetworkStream(m _networkSocket, false);

// write
m_networkConnec tion.Write(arra yOfBytes, 0, arrayOfBytes.Le ngth);
m_networkConnec tion.Flush();

// close
m_networkConnec tion.Flush();
m_networkConnec tion.Close();
m_networkSocket .Close();
All fine & good, but nothing shows up on the other side. If I put a delay
between Flush() and Close() it suddenly starts to work.

So is Flush() is a no-op?

Close() (for both Socket and NetworkStream) has an optional "timeout" value
(an Int32), which is 'the amount of time to wait for data to be sent'. I
_assume_ that's milliseconds, but does anyone know for sure?

That begs the question, however, of just how long do I wait? How do I know
my data has been sent and it's safe for me to close the connection?

Thanks!

al

--
Al Dunstan, Software Engineer
OptiMetrics, Inc.
3115 Professional Drive
Ann Arbor, MI 48104-5131
Aug 27 '08 #1
3 4099
On Wed, 27 Aug 2008 12:16:19 -0700, A. W. Dunstan <no@spam.thanks wrote:
[...]
All fine & good, but nothing shows up on the other side. If I put a
delay
between Flush() and Close() it suddenly starts to work.

So is Flush() is a no-op?

Close() (for both Socket and NetworkStream) has an optional "timeout"
value
(an Int32), which is 'the amount of time to wait for data to be sent'. I
_assume_ that's milliseconds, but does anyone know for sure?
From the MSDN documentation: "Wait up to timeout seconds to send any
remaining data, then close the socket". But that's not really what you
want.
That begs the question, however, of just how long do I wait? How do I
know
my data has been sent and it's safe for me to close the connection?
The correct way to manage the connection is to call
Socket.Shutdown (SocketShutdown .Send) when you're done sending data, and
then call Socket.Receive( ) until you get return value of 0.

I would not expect Stream.Flush() to do much of anything. The Socket
class is likely to be passing data off to the network driver as fast as it
can. Any delays in transmission are likely due to the Nagle algorithm,
which is responsible for coalescing data sent on a TCP connection, to
ensure efficient use of the connection.

Most likely what was happening in your example is that the socket was
being closed before the network driver got around to sending the data (it
was waiting a few hundred ms to see if you sent any more that it could
combine with what you'd already sent), aborting the transfer. There are
different ways to deal with this, but the best way is to manage the
connection in the expected way.

Pete
Aug 27 '08 #2
Peter Duniho wrote:
>Close() (for both Socket and NetworkStream) has an optional "timeout"
value
(an Int32), which is 'the amount of time to wait for data to be sent'. I
_assume_ that's milliseconds, but does anyone know for sure?

From the MSDN documentation: "Wait up to timeout seconds to send any
remaining data, then close the socket". But that's not really what you
want.
Ah - I'd been relying on the Visual Studio online help which made no mention
of units.
>That begs the question, however, of just how long do I wait? How do I
know
my data has been sent and it's safe for me to close the connection?

The correct way to manage the connection is to call
Socket.Shutdown (SocketShutdown .Send) when you're done sending data, and
then call Socket.Receive( ) until you get return value of 0.

I would not expect Stream.Flush() to do much of anything. The Socket
class is likely to be passing data off to the network driver as fast as it
can. Any delays in transmission are likely due to the Nagle algorithm,
which is responsible for coalescing data sent on a TCP connection, to
ensure efficient use of the connection.

Most likely what was happening in your example is that the socket was
being closed before the network driver got around to sending the data (it
was waiting a few hundred ms to see if you sent any more that it could
combine with what you'd already sent), aborting the transfer. There are
different ways to deal with this, but the best way is to manage the
connection in the expected way.
Thanks! I'll give that a try shortly.

My transmission is purely one-way - send only. After calling Shutdown() do
I still need to call Receive()? Or is Shutdown() followed by Close()
sufficient to tell the socket "I'm done sending - finish up"?

--
Al Dunstan, Software Engineer
OptiMetrics, Inc.
3115 Professional Drive
Ann Arbor, MI 48104-5131
Aug 28 '08 #3
On Thu, 28 Aug 2008 07:05:10 -0700, A. W. Dunstan <no@spam.thanks wrote:
[...]
My transmission is purely one-way - send only. After calling Shutdown()
do
I still need to call Receive()? Or is Shutdown() followed by Close()
sufficient to tell the socket "I'm done sending - finish up"?
No, you need to call Receive(). As an alternative, you can set the
DontLinger socket option to false and specify a non-zero timeout (see
Socket.SetSocke tOption()). But even in that case, if the timeout is
exceeded, transmission of the data will be aborted. To ensure that your
end has done everything it can to send the data, you need to call
Receive() and wait for the 0 byte return value.

That assumes, of course, that you want that behavior. For some
applications, a timeout in completing the send is appropriate, and you
would in fact be better off with the DontLinger approach. It just depends
on what you want your network i/o to do.

Pete
Aug 28 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1812
by: drs | last post by:
Hi, I have a program which opens a socket server in a thread. I need for the server to listen on the socket for a certain amount of time (say, ten seconds or so) and then close it, and am wondering if there is a good way to close the socket other than sending it a message from another thread to close itself. That is, I am looking for a way to forcably kill a socket from a second thread, not to send it a message to kill itself. ...
3
9090
by: Daniel | last post by:
TcpClient close() method socket leak when i use TcpClient to open a connection, send data and close the TcpClient with myTcpClientInstance.Close(); it takes 60 seconds for the actual socket on the client machine to close per my network app the computer fills up w/ thousands of these :0 TCP foobox:8888 localhost:2188 TIME_WAIT :0 TCP foobox:8888 localhost:2189 TIME_WAIT :0 TCP foobox:8888 localhost:2190 TIME_WAIT
0
9970
by: Steve - DND | last post by:
We are continually receiving timeout, and "Unable to write data to the transport connection" errors while using the System.Net.HttpWebRequest class from an ASP.Net web page. Below are the two errors we continue to receive: Source: System Message: The operation has timed-out. Target Function: System.Net.WebResponse GetResponse()
4
18111
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call shutdown and close asynchronously if possible.
8
41378
by: Claire | last post by:
I'm trying to debug my network application ie I want to check my error handling when the connection is broken. Im using 127.0.0.1 as the connection address. Unfortunately, the client socket goes into a CLOSE_WAIT state ad infinitum and never closes fully until my client and server applications shut down. Ive disabled lingeroptions. Is there anything else easy that i can do to force the loopback to close immediately?
3
6460
by: Helge Jensen | last post by:
I am implementing a protocol which transmits messages. The messages are most naturally transferred using the a Stream so the protocol can communicate over serial-ports, network links, .... If the other party never answers I must timeout -- not block, and this gives me a problem, since the Stream concept in .NET does not reflect timeouts. If a timeout occurs I will still need to use the same Stream for more messages, for example re-sends....
4
11381
by: Haim | last post by:
it is very strange for me that a simple event of closing socket that was in the the winsock object of vb6 , i didn't found yet in the vb.net the only way i found is to try to send something to the socket and if i got error then the socket is closed. there must be a way to get this event without trying to send something , since it is in the lower level
0
1040
by: uneasyrider | last post by:
OK I'm about to pull my hair out on this one. I've got a socket created that sends a network stream of data from a listview to an open port. It works great!! I'm getting ACK's back from the server with no problem. I can even send multiple messages at a time. HOWEVER... If I highlight one item and send it... then highlight another item immediately afterwards and send it... I get a connection refused. If I send one item, wait about 7-8...
2
4526
by: Zytan | last post by:
I just had the problem occur again, with NetworkStream.Write() doing its thing with a timeout... and it just sits and waits and waits and waits... it never times outs. So, I shut the server down just to see if THAT will make it at least end the function call and continue (since it's a synchronous call, so the program is delayed until it returns), and even THAT doesn't make the call end. It just sits and waits... Even IF I have a bug...
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8337
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8628
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2754
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.