Socket throws nullreferenceexception while asynchrously receiving data
So I have my server-client protocol and they cannot perfectly but when the client has received data from the server it throws a nullreference exception, this code handles the received data:
private void AsyncReceive(IAsyncResult result)
{
int bytesTransferred;
try
{
bytesTransferred = _handle.EndReceive(result); //throws the exception
if (bytesTransferred <= 0)
throw new Exception("no bytes transferred");
}
catch (NullReferenceException)
{
return;
}
catch (ObjectDisposedException)
{
return;
}
catch (Exception)
{
Disconnect();
return;
}
byte[] received = new byte[bytesTransferred];
try
{
Array.Copy(_readBuffer, received, received.Length);
}
catch (Exception ex)
{
OnClientFail(ex);
return;
}
lock (_readBuffers)
{
_readBuffers.Enqueue(received);
}
lock (_readingPacketsLock)
{
if (!_readingPackets)
{
_readingPackets = true;
ThreadPool.QueueUserWorkItem(AsyncReceive);
}
}
try
{
_handle.BeginReceive(_readBuffer, 0, _readBuffer.Length, SocketFlags.None, AsyncReceive, null);
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
OnClientFail(ex);
}
}
So the line bytesTransferred = _handle.EndReceive(result);
throws the exception. I should also note that I am NOT using an ordinary socket, i'm using a ProxySocket(extensioh of the socket class) which can be found here: ProxySocket and here is how the client starts the datahandling: ` protected void Connect(string ip, ushort port) { try { Disconnect();
_handle = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_handle.SetKeepAliveEx(KEEP_ALIVE_INTERVAL, KEEP_ALIVE_TIME);
_handle.ProxyType = ProxyTypes.Https;
_handle.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 54973);
_handle.Connect(ip, port);
if (_handle.Connected)
{
_handle.BeginReceive(_readBuffer, 0, _readBuffer.Length, SocketFlags.None, AsyncReceive, null);
OnClientState(true);
}
}
catch (Exception ex)
{
OnClientFail(ex);
}
} `
If I need to provide more data, you can ask me in a comment.
Thanks
This is result:
+ _handle {Org.Mentalis.Network.ProxySocket.ProxySocket} Org.Mentalis.Network.ProxySocket.ProxySocket
bytesTransferred 0 int
result {System.Net.Sockets.OverlappedAsyncResult} System.IAsyncResult {System.Net.Sockets.OverlappedAsyncResult}
AsyncCallback {Method = {Void AsyncReceive(System.IAsyncResult)}} System.AsyncCallback AsyncState null object
AsyncWaitHandle {System.Threading.ManualResetEvent} System.Threading.WaitHandle {System.Threading.ManualResetEvent} CompletedSynchronously false bool IsCompleted true bool
Static members
Non-Public members
this {_4ng3l.Core.Networking.G0DClient} _4ng3l.Core.Networking.Client {_4ng3l.Core.Networking.G0DClient}