Null socket object on callback

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi. I'm working with asyncronous communication with sockets. I have the
following methods:

internal void SendData(Channel channel, byte[] buffer, int offset, int count)
{
if(channel != null && channel.Socket != null && channel.Socket.Connected)
channel.Socket.BeginSend(buffer, offset, count, SocketFlags.None,
new AsyncCallback(OnDataSent), channel);
}

private void OnDataSent(IAsyncResult asyncResult)
{
if(asyncResult != null && asyncResult.AsyncState != null)
{
Channel channel = (Channel)asyncResult.AsyncState;
ushort bytesSent = (ushort)channel.Socket.EndSend(asyncResult);
...
}
}

The Channel class is a custom class that holds a reference to a Socket
object. First I call the SendData method, that calls the BeginSend method on
the Socket object. When the socket ends sending the data, it calls the
OnDataSent method. The problem is that when I try to call the EndSend method,
the Socket object is null. I don't have any control over it since is the
framework that calls the method. When I don't test if the Socket object is a
null reference, I get the NullReferenceException. When I test, I get a
SocketException with the message 'An existing connection was forcibly closed
by the remote host'. Neither the server nor the client has intentionally
closed the socket.

In other words, all the problems reside in the fact that the Socket object
is null. Do you have any idea about what could be causing this behaviour?
Could the network topology have any influence?

Thanks
 
If network topology has an influence you it'll be difficult even to
establish connection :8-)

Some time ago I've had similar exception in the similar situation. In my
case when excpetion happened I was closing connection and setting socket to
null.
How do you handle situations when there is an exception?
 
Back
Top