473,795 Members | 2,867 Online
Bytes | Software Development & Data Engineering Community
+ 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 myCompleteMessa ge = "";
int numberOfBytesRe ad;

numberOfBytesRe ad = myNetworkStream .EndRead(ar);
myCompleteMessa ge =
String.Concat(m yCompleteMessag e,
Encoding.ASCII. GetString(myRea dBuffer, 0, numberOfBytesRe ad));

// message received may be larger than buffer size so loop through
until you have it all.
while(myNetwork Stream.DataAvai lable){

myNetworkStream .BeginRead(myRe adBuffer, 0,
myReadBuffer.Le ngth,
new
AsyncCallback(N etworkStream_AS ync_Send_Receiv e.myReadCallBac k),
myNetworkStream );

}

// Print out the received message to the console.
Console.WriteLi ne("You received the following message : " +
myCompleteMessa ge);
}
I wonder, how myCompleteMessa ge 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(myNetwor kStream.DataAva ilable){...}") , I would be most
grateful.

Best regards

DC
Nov 15 '05 #1
2 16689
dc@upsize.de (DC) wrote in message news:<5b******* *************** ****@posting.go ogle.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 myCompleteMessa ge 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(myNetwor kStream.DataAva ilable){...}") , 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.goo gle.com>...
dc@upsize.de (DC) wrote in message news:<5b******* *************** ****@posting.go ogle.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 myCompleteMessa ge 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(myNetwor kStream.DataAva ilable){...}") , 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
3369
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
7208
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 one of these things and it WON'T read data. If I set a breakpoint in my EndRead callback, it never goes off. NOTHING is different from anywhere else I use this class, its just this one place. Now, if I create a second constructor for my class...
34
7329
by: Mark Kamoski | last post by:
Hi-- Please help. I need a code sample for bubble sort. Thank you. --Mark
3
5044
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 Event I think the whole OnThreadException routine could be replaced with two lines of code: if (ShowThreadExceptionDialog(t.Exception) == DialogResult.Abort)
5
2290
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 collection object -- say, a dictionary. Populating that collection object with custom objects, say, Person. What I really want to see is how to populate the properties of those Person objects from a datasource: instantiate one Person, fill...
17
19324
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 build but did not see anything like dll. When I looked at the command line tools and sample, I only saw c code not vb. for dll the environment I have is
0
1149
by: SanjeevN | last post by:
MSDN has sample code for interacting with the MetaWeblog API C# Sample - complete and compiles. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msnspaces/MetaWeblogAPI_CSharp_Code_Sample.asp VB sample - is incomplete and incorrect. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msnspaces/MetaWeblogAPI_VB_Code_Sample.asp Can someone post the equivalent VB code just for this snippet?
2
1329
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
5661
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) and type ?dedrow(c), It says basically the same thing: Run-time exception thrown : System.ArgumentException - Column 'TICKETNO' does not belong to table TICKET_DEDUCTIONS.
0
9522
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
10448
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...
0
10217
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10167
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
9046
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
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
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2922
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.