BeginConnect/EndConnect + BeginReceive Exception  
Author Message
bilsa





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Hi There!

I'm getting this strange behaviour when using async sockets with c# .Net 3.0
The problem goes like this:

I start to connect to a tcp server with BeginConnect(), once the ConnectCallback is called, I finish the connection with EndConnect(). This then fires an event "OnConnected".

A handler for OnConnected, receives the socket that I just performed EndConnect() on, and immediately starts BeginReceive() on it.

Now the problem is that BeginReceive() throws me an exception:

"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a send call) no address was supplied"

But, EndConnect() finished without any exceptions So eh, what is the problem.

Now, If I wait for about 5 seconds before making the BeginReceive(), then it works just fine, a simble Thread.Sleep(5000) makes the BeginReceive() work fine.

I'm thinking maybe the server is sending acknowledge data back and forth, and somehow ****s things up Though, if I use for example java NIO completion ports, then everything works fine and there is no delay at all.

Any help on this would be appreciated!





.NET Development23  
 
 
bilsa





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Not sure it it helps any, but here is how the code snippets look:

<code>

//This is the BeginConnect method, that tries to connect to the server
private void BeginConnect()
{
try
{
//Setup the socket to connect to
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(LocalInetAddress);
//Now start connecting to the remote with a new thread
_socket.BeginConnect(_remoteInetAddress, new AsyncCallback(ConnectCallback), this);
}
catch (Exception outerException)
{
//Failed to setup socket to the remote address, so don't bother trying
FireOnException(outerException);
}
}

//This is the Callback method for BeginConnect
private void ConnectCallback(IAsyncResult ar)
{
if (!IsDisposed)
{
BaseSocketConnection connection = null;
ClientSocketConnector connector = null;

try
{
//Get the connector that started this request
connector = (ClientSocketConnector)ar.AsyncState;
//Finish and establish the connection
connector.Socket.EndConnect(ar);

//Set the buffer size for recieving and sending packets
connector.Socket.ReceiveBufferSize = Host.SocketBufferSize;
connector.Socket.SendBufferSize = Host.SocketBufferSize;

//Create a new connection to a server
connection = new ClientSocketConnection(Host, this, connector.Socket, ProtocolFactory());
//Debugging
System.Console.WriteLine("Connected to... " + LocalInetAddress);

/////////////////////////// PROBLEM CODE: ///////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//If I add BeginReceive here,,, the exception is thrown
//BUT, if I add Thread.Sleep(5000); then everything works fine.
//connector.Socket.BeginReceive(....);
////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////// END ///////////////////////////////////////////

//Add the connection
AddSocketConnection(connection);
FireOnAccepted(connection);
}
catch (Exception outerException)
{
if (connection != null)
{
//Hum, we established a connection to the remote, but still some error...
//So disconnect!
try
{
connection.BeginDisconnecting(outerException);
}
catch (Exception innerException)
{
Host.FireOnException(innerException);
}
}
else
{
FireOnException(outerException);
}

}
}
}

</code>


 
 
bilsa





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Someone please This is bugging the hell out of me ;/


 
 
RizwanSharp





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Hmm, Sorry Bilsa can't say more but truely it seems like a Weird problem really, May be some System.Net namespace team member can tell you what's going behind the scenes and why does it need a delay if it has been already in Connected state....

If no body replies then have to live with Thread.Sleep() :P

Best of Luck,

Rizwan



 
 
bilsa





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

yep, thx anyway thogh


 
 
Durgaprasad Gorti





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

I will take a look at this today sometime
Thanks for your patience. From what I can gather - it should work



 
 
bilsa





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Thanks, here is some more info on the exceptions, some internal socket exceptions:

------------------------------------------------------------------------------------------
THROWN EXCEPTION BY socket.BeginReceive(...)
------------------------------------------------------------------------------------------
Socket.BeginReceive(...)

Message "A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied" string

StackTrace " at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)\r\n at Storm.Net.SocketStream.RecieveData(BaseSocketHost host, DataArgs sendArgs)

TargetSite {System.IAsyncResult BeginReceive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags, System.AsyncCallback, System.Object)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}

error code:10057
socket error code: NotConnected
------------------------------------------------------------------------------------------


------------------------------------------------------------------------------------------
INTERNAL SOCKET EXCEPTION
------------------------------------------------------------------------------------------
Socket.MulticastLoopback:

Message: "An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call"

StackTrace " at System.Net.Sockets.Socket.GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)\r\n at System.Net.Sockets.Socket.get_MulticastLoopback()" string

TargetSite {System.Object GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}

error code: 10042
SocketErrorCode: ProtocolOption
Exception type: System.Net.Sockets.SocketError
-------------------------------------------------------------------------------------------

What I'm a little confused about, is why i'm not connected when I just previously did connect, and everything went fine

Thanks!


 
 
jkimbu





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

I wonder if the original poster ever got an answer to this question I've had the same problem, I've tried getting the two threads to handshake with each other, I've tried making the Connect() synchronous instead of asynchronous (which makes the async reading and writing fail)... I can fix the problem with that Sleep(100), but since we have no way of knowing what the problem *really* is, there's no way to know if Sleep(100) will always be enough.
 
 
Grumbler





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

Hi there,

I have the same problem on a slow connection.

For me, 5 seconds are sometimes not enough.

I think it is a bug in the Socket framework.


 
 
SysEngr62





PostPosted: .NET Framework Networking and Communication, BeginConnect/EndConnect + BeginReceive Exception Top

I have been having a related problem. I adapted some code from the VS help that will detect the not connected after a successful connect condition (see below). Unfortunately it doesn't help much the thread.sleep solution doesn't help me much.

code for detection function follows:

Private Function TCPSendSocketConnected(ByRef S As Socket) As Boolean

Dim Answer As Boolean = False

Try

Dim tmp(0) As Byte

S.Blocking = False

S.Send(tmp, 0, 0)

Answer = True

Catch e As SocketException

' 10035 == WSAEWOULDBLOCK

If e.NativeErrorCode.Equals(10035) Then

'Console.WriteLine("Still Connected, but the Send would block")

Answer = True

Else

'Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode)

Answer = False

End If

End Try

Return Answer

End Function