473,471 Members | 2,175 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

NetworkStream / BeginRead / EndRead / Dataavailable: can't understand MSDN code sample

DC
Hi,

I need to asynchronously read from a network (TCP) stream, and I am
having trouble with retrieving whole blocks; I get a break in the data
block every 1460 bytes which relates to network packet sizes I guess.

To get this fixed, I am trying to follow an example in the MSDN, which
pretty much resembles what I want to do. Since the code (I can't do
this in a static class for example) is not 100% what I need, I
certainly would like to understand what I am doing, but I guess I am
lacking some fundamentals of asynchronous programming since I simply
do not understand the code snippet. Here it is:
public static void myReadCallBack(IAsyncResult ar ){

NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
byte[] myReadBuffer = new byte[1024];
String myCompleteMessage = "";
int numberOfBytesRead;

numberOfBytesRead = myNetworkStream.EndRead(ar);
myCompleteMessage =
String.Concat(myCompleteMessage,
Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

// message received may be larger than buffer size so loop through
until you have it all.
while(myNetworkStream.DataAvailable){

myNetworkStream.BeginRead(myReadBuffer, 0,
myReadBuffer.Length,
new
AsyncCallback(NetworkStream_ASync_Send_Receive.myR eadCallBack),
myNetworkStream);

}

// Print out the received message to the console.
Console.WriteLine("You received the following message : " +
myCompleteMessage);
}
I wonder, how myCompleteMessage can ever add up to the complete
message, since it will be reinitialized at every callback, won't it?

If somebody can help me to understand this (what happens
"while(myNetworkStream.DataAvailable){...}") , I would be most
grateful.

Best regards

DC
Nov 15 '05 #1
2 16623
dc@upsize.de (DC) wrote in message news:<5b**************************@posting.google. com>...
Hi,

I need to asynchronously read from a network (TCP) stream, and I am
having trouble with retrieving whole blocks; I get a break in the data
block every 1460 bytes which relates to network packet sizes I guess.
I wonder, how myCompleteMessage can ever add up to the complete
message, since it will be reinitialized at every callback, won't it?

If somebody can help me to understand this (what happens
"while(myNetworkStream.DataAvailable){...}") , I would be most
grateful.

DC -

This code snippet has problems at a couple of different levels. As
you point out, when you iterate through a method, you don't want to
reinitialize the buffer piecing the data together each time.
Initialize it at the global level and add each piece of data with each
iteration.

A second problem is the DataAvailable property. This value will
only be true if data is waiting in the socket buffer for you to read.
It doesn't know if more data is on the way and might be delayed. All
it knows is that no data is available at that moment.

The problem you must solve is how to let one end of the
communication know when it has received all of the data the other end
sent. There are three common methods used to do this:

1. If only one piece of data must be sent in the session, after the
sender sends the data it should close the socket. The receiving end
can loop on Reading data until an EndRead() method returns 0 bytes, it
then knows all of the data has been received and the connection has
been closed.

2. If multiple pieces of data must be sent in a single session, the
sender can send the size of each data element before the actual data
element. The receiving end can then read the data size value, and then
loop on Begin/End Read() methods until it knows all of the data bytes
have been received (using a counter that is not reinitialized on each
iteration).

3. Another method of sending multiple data elements is to use a
delimiter character to separate the data elements. The receiving end
reads data from the stream until it recognizes a delimiter character
(which should be something that is not normally seen in the data).
When it sees a delimiter character it knows all of the data has been
received.

I demonstrate each of these methods in my book. You can freely
download the example code from the Sybex web site to get a feel for
how to use each method. Hope this helps solve your problem.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyT...471433012.html
Nov 15 '05 #2
DC
Thanks a lot for your pointers, Rich. I more or less followed the
third method you propsed.

Best regards

DC
ri*******@juno.com (Rich Blum) wrote in message news:<cc*************************@posting.google.c om>...
dc@upsize.de (DC) wrote in message news:<5b**************************@posting.google. com>...
Hi,

I need to asynchronously read from a network (TCP) stream, and I am
having trouble with retrieving whole blocks; I get a break in the data
block every 1460 bytes which relates to network packet sizes I guess.
I wonder, how myCompleteMessage can ever add up to the complete
message, since it will be reinitialized at every callback, won't it?

If somebody can help me to understand this (what happens
"while(myNetworkStream.DataAvailable){...}") , I would be most
grateful.

DC -

This code snippet has problems at a couple of different levels. As
you point out, when you iterate through a method, you don't want to
reinitialize the buffer piecing the data together each time.
Initialize it at the global level and add each piece of data with each
iteration.

A second problem is the DataAvailable property. This value will
only be true if data is waiting in the socket buffer for you to read.
It doesn't know if more data is on the way and might be delayed. All
it knows is that no data is available at that moment.

The problem you must solve is how to let one end of the
communication know when it has received all of the data the other end
sent. There are three common methods used to do this:

1. If only one piece of data must be sent in the session, after the
sender sends the data it should close the socket. The receiving end
can loop on Reading data until an EndRead() method returns 0 bytes, it
then knows all of the data has been received and the connection has
been closed.

2. If multiple pieces of data must be sent in a single session, the
sender can send the size of each data element before the actual data
element. The receiving end can then read the data size value, and then
loop on Begin/End Read() methods until it knows all of the data bytes
have been received (using a counter that is not reinitialized on each
iteration).

3. Another method of sending multiple data elements is to use a
delimiter character to separate the data elements. The receiving end
reads data from the stream until it recognizes a delimiter character
(which should be something that is not normally seen in the data).
When it sees a delimiter character it knows all of the data has been
received.

I demonstrate each of these methods in my book. You can freely
download the example code from the Sybex web site to get a feel for
how to use each method. Hope this helps solve your problem.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyT...471433012.html

Nov 15 '05 #3

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

Similar topics

1
by: Kyle Jedrusiak | last post by:
Need the correct usage pattern for something like a chat program. Don't want any threading issues or stack problems. Kyle!
4
by: 0to60 | last post by:
I have a class that wraps a TcpClient object and manages all the async reading of the socket. It works really nice, and I use it all over the place. But there's this ONE INSTANCE where I create...
34
by: Mark Kamoski | last post by:
Hi-- Please help. I need a code sample for bubble sort. Thank you. --Mark
3
by: orekinbck | last post by:
Hi There I'm probably missing something fundamental here but I don't understand the code in the OnThreadException routine, which is found in MSDN under the topic: Application.ThreadException...
5
by: | last post by:
Trying to learn about manipulating collections of objects, and populating these objects dynamically from datasources. Could someone post a code sample that shows the following: Instantiating a...
17
by: gg | last post by:
how can one compile vb code into dll? The vstdio build project it tends to build exe. When I looked at the build in help I did not find anything about configuring for DLL. I even try custom...
0
by: SanjeevN | last post by:
MSDN has sample code for interacting with the MetaWeblog API C# Sample - complete and compiles....
2
by: Solo.Wolve | last post by:
while(TRUE){ while (turn != 0) /* Should here be a semicolon ( ; ) to make while a NULL repetition? */ critical_region(); turn = 1; noncritical_region(); } /* (a) PROCESS 0 */
2
by: Ronald S. Cook | last post by:
In the code below, I get a runtime error where indicated. The error is: "Column 'TICKETNO' does not belong to table TICKET_DEDUCTIONS." If I put a breakpoint on that line (so not yet executed)...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
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...
1
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...
0
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...
0
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 ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.