# [.net] BeginSend() returning possible error

## Recommended Posts

Afr0m@n    100
I'm having a problem with this code:
		public void WriteLine(Socket SocketHandle, string Data)
{
byte[] DataArray = new byte[Data.Length];
DataArray = Encoding.ASCII.GetBytes(Data.ToCharArray());

SocketHandle.BeginSend(DataArray, 0, DataArray.Length, SocketFlags.None, new AsyncCallback(WriteCallback), SocketHandle);
}

private void WriteCallback(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
s.EndConnect(ar);
}

MSVS 2005 Express tells me that when I call WriteLine(), the BeginSend function doesn't return anything. The actual error message looks like this: "Exception System.ArgumentException was thrown in debugee: The IAsyncResult object was not returned from the corresponding asynchronous method on this class." That error message points to the line that goes: "s.EndConnect(ar);" I'm suspecting that BeginReceive() is returning an error, but I've no idea how to check for it. It should probably be done in the callback function, but what form is the error going to be in? Also, if an error is generated, then why is that? Can anyone see anything wrong with my code? Thanks in advance!

##### Share on other sites
Bob Janova    769
Um, that's because EndConnect() should be called in the callback to BeginConnect()! If you're trying to disconnect the socket after writing, use Close() instead.

##### Share on other sites
Afr0m@n    100
:O

That worked! Thanks alot!

Quote from MSDN:

[C#] allDone.Set();Socket s = (Socket) ar.AsyncState;s.EndConnect(ar);StateObject so2 = new StateObject();so2.workSocket = s;byte[] buff = Encoding.ASCII.GetBytes("This is a test");s.BeginSend(buff, 0, buff.Length,0,                      new AsyncCallback(Async_Send_Receive.Send_Callback), so2);

MSDN Article on BeginSend