Socket在异步接收数据时抛出nullreferenceexception
所以我有我的服务器 - 客户端协议,他们不能完美的,但是当客户端从服务器接收到数据时,它会抛出一个nullreference异常,这段代码处理接收到的数据:
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);
}
}
所以行bytesTransferred = _handle.EndReceive(result);
抛出异常。 我还应该注意到,我没有使用普通的套接字,我使用了ProxySocket(套接字类的extensioh),它可以在这里找到:ProxySocket,这里是客户端如何启动数据处理:`protected void Connect(string ip ,ushort端口){尝试{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);
}
} `
如果我需要提供更多数据,可以在评论中问我。
谢谢
这是结果:
+ _handle {Org.Mentalis.Network.ProxySocket.ProxySocket} Org.Mentalis.Network.ProxySocket.ProxySocket
bytesTransferred 0 int
结果{System.Net.Sockets.OverlappedAsyncResult} System.IAsyncResult {System.Net.Sockets.OverlappedAsyncResult}
AsyncCallback {Method = {Void AsyncReceive(System.IAsyncResult)}} System.AsyncCallback AsyncState null对象
AsyncWaitHandle {System.Threading.ManualResetEvent} System.Threading.WaitHandle {System.Threading.ManualResetEvent} CompletedSynchronously false bool IsCompleted true bool
静态成员
非公众成员
这个{_4ng3l.Core.Networking.G0DClient} _4ng3l.Core.Networking.Client {_4ng3l.Core.Networking.G0DClient}
上一篇: Socket throws nullreferenceexception while asynchrously receiving data
下一篇: C# Null Conditional Operator alternative (conditional assignment)?