-
August 1st, 2012, 02:28 AM
#1
Problems with BeginReceive Callback
Hi everybody
I am dealing with a strange problem when closing a socket connection. I am using an asynchronous receive and I specified, as is MSDN's suggestion, a user-defined object as the last parameter in my BeginReceive(). I expect, as MSDN says, this same object to be passed in the State field of the IAsynchResult parameter of the Callback function I specified in my BeginReceive () call. But , as I close the connection, and the tcp layer as usual sends me a zero-length packet, the Callback function is called but the State field is the Socket native object which received the close and not the user-defined object I specified in the BeginReceive.
This seems to be in contrast with MSDN specifications. What am I doing wrong ?
-
August 1st, 2012, 07:32 AM
#2
Re: Problems with BeginReceive Callback
Originally Posted by towmtdj
Hi everybody
Hi.
Originally Posted by towmtdj
What am I doing wrong ?
Well, it would help if you posted some code - in particular, the call to BeginReceive(), and the corresponding callback method.
Are you sure you've passed the right object and that you're checking in the right callback, or that there aren't any other methods invoking the same callback, possibly sending a Socket instead, and you don't expect it?
Take a look at the MSDN example at this page.
Here's the condensed version:
Code:
// some class that holds some user data, like the socket, or the buffer, and whatever
public class StateObject
{
// ...
}
Code:
// A listen callback, invoked by BeginAccept(), which passed a socket as user state object
public static void Listen_Callback(IAsyncResult ar)
{
//...
Socket s = (Socket) ar.AsyncState; // retrieve the socket (normally, you know what type to cast to)
Socket s2 = s.EndAccept(ar); // end operation, get the new socket
StateObject state = new StateObject(); // create and init the StateObject instance
state.workSocket = s2;
s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
new AsyncCallback(Read_Callback), state); // and pass it instead
}
Code:
// the read callback retrieves the StateObject instance
public static void Read_Callback(IAsyncResult ar)
{
StateObject state = (StateObject) ar.AsyncState;
//...
}
Last edited by TheGreatCthulhu; August 1st, 2012 at 07:36 AM.
-
August 1st, 2012, 08:51 AM
#3
Re: Problems with BeginReceive Callback
Hi TheGreatCThulhu, thank you for answering .
I have to apologize 'cause I have just realized that I simply passed the wrong argument.
Sorry for the annoyance, and thank you again.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|