473,583 Members | 3,386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

BeginReceive Async network socket example

Dear Readers,

I am in the process of implementing a non-blocking ASYNC TCP client
using the .Net socket class. I am a little confused by the MSDN
example. I have pasted the code here.

private static void ReceiveCallback ( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocke t;
// Read data from the remote device.
int bytesRead = client.EndRecei ve(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so
far.
state.sb.Append (Encoding.ASCII .GetString(stat e.buffer,0,byte sRead));
// Get the rest of the data.
client.BeginRec eive(state.buff er,0,StateObjec t.BufferSize,0,
new AsyncCallback(R eceiveCallback) , state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Lengt h > 1) {
response = state.sb.ToStri ng();
}
}
} catch (Exception e) {
Console.WriteLi ne(e.ToString() );
}
}

In the callback if the number of bytes read is zero the else branch is
used.

What conditions do you expect here? Ie will I come through here once
the reads finished or is this branch more to catch the remote end
point hanging up?

Could someone explain this a better as all my data appears to be read
correctly in the first branch.

Thanks

Mark
Nov 16 '05 #1
1 13696
Mark Smith <sh******@yahoo .com.au> wrote:
I am in the process of implementing a non-blocking ASYNC TCP client
using the .Net socket class. I am a little confused by the MSDN
example. I have pasted the code here.

private static void ReceiveCallback ( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocke t;
// Read data from the remote device.
int bytesRead = client.EndRecei ve(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so
far.
state.sb.Append (Encoding.ASCII .GetString(stat e.buffer,0,byte sRead));
// Get the rest of the data.
client.BeginRec eive(state.buff er,0,StateObjec t.BufferSize,0,
new AsyncCallback(R eceiveCallback) , state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Lengt h > 1) {
response = state.sb.ToStri ng();
}
}
} catch (Exception e) {
Console.WriteLi ne(e.ToString() );
}
}

In the callback if the number of bytes read is zero the else branch is
used.

What conditions do you expect here? Ie will I come through here once
the reads finished or is this branch more to catch the remote end
point hanging up?

Could someone explain this a better as all my data appears to be read
correctly in the first branch.


I'm not entirely sure what you're asking. Calling Read once (or
anything similar) isn't guaranteed to get all the data in one go.
(Imagine you're downloading hundreds of megs - you may well not *need*
to have it all at one point in time.) Therefore you may well have more
data still to read. When a reading method returns 0, that means that
you've reached the end of the stream, or the socket has been closed,
etc - it means you're done.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

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

Similar topics

0
1216
by: K_Lee | last post by:
While trying to understand some issues to python's implementation of Socket, I recorded an outline to Python's socket object interface to the native implementation in a webblog type documents in our website. Just like to share it with others in case you find it useful. Each of the following lines are links to source code where the...
7
1525
by: selekta | last post by:
hi, i've recently started to deal a little bit with tcp/ip-socket-programming (linux). Now i've written a little test-program (as displayed further down). When i'm trying to compile it the gcc-compiler return "parse error in l.23/.24 before token '='. " the line before those two ( host_addr.sin_family = AF_INET;) is acepted without any...
0
3102
by: Thomas Zöchling | last post by:
Hat jemand (schlechte) Erfahrungen mit Asynchronen NetworkStreams gemacht? In meiner Serveranwendung scheint die BeginRead Methode des NetworkStreams manchnmal den Stream nicht fertig zu lesen. ... socket = socketForClient; buffer = new byte; networkStream = new NetworkStream(socketForClient); callbackRead = new...
8
12653
by: rawCoder | last post by:
Hi All, I need some advanced samples or references for passing custom objects over the network using sockets. Without using Remoting what are other options in .NET Framework for this binary serialization. Thank You rawCoder
2
1988
by: pigeonrandle | last post by:
Hi, I'm looking a TCP guru, so i apologise for any campanologists i may have attracted by my title. I'm using the following example code from MS (perhaps i am doomed from the outset!) .. Server: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconnon-blockingserversocketexample.asp
2
2263
by: Marcel Brekelmans | last post by:
Hi, I use a socket to receive data from a certain process. I use the asynchronous operations BeginReceive() and EndReceive(), with a callback in BeginReceive. Now all documentation says that the callback, as specified in BeginReceive, is called as soon as 'the data is received'. But this is rather vague: when exactly is that moment if you...
3
6756
by: Sir Psycho | last post by:
Hi, For some reason, when i step over this code, it returns the full byte stream im expecting from the server, however when I let it run with no intervention, it only seems to grab a small chunk on the stream. What am I doing wrong? There is more code than this, but this is the problem code.
0
1390
by: Blog the Haggis | last post by:
Hi all, I've written a program which distributes binary data to a number of clients via TCP. The program runs perfectly unless one of the client programs hangs and then it freezes while waiting for the socket.send(Data) method to complete. I've tried all of these socket options to overcome this event: 'Set send timeout to 2 seconds:
4
2190
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I need to do a simple asych post back to validate that an id is unique. I do not want to post back the entire page for this, but i want to make this part of the clientside validators. 1. i already have a custom validator that checks for a correctly formatted id and the javascript works w/o problem. Any help would be appreciated. --...
0
7894
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...
0
7821
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...
0
8172
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. ...
0
8320
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...
1
7929
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...
0
6577
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...
0
3814
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...
1
2328
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
1
1424
muto222
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.