所以我有我的服务器 - 客户端协议,它们不能完美但是当客户端从服务器接收到数据时会抛出一个空引用异常,这段代码处理接收到的数据:
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(套接字类的扩展),可以在这里找到:ProxySocket以及客户端如何启动数据处理:
`protected void Connect(string ip,ushort port)
{
尝试
{
断开();
_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
result {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}