private void Process(object s, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError == SocketError.Success)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
_endPoint = (IPEndPoint)_handle.RemoteEndPoint;
Connected = true;
_items[0].SetBuffer(new byte[BufferSize], 0, BufferSize);
_asyncOperation.Post(x => OnClientState(true), null);
if (!_handle.ReceiveAsync(e))
Process(null, e);
break;
case SocketAsyncOperation.Receive:
if (!Connected)
return;
if (e.BytesTransferred != 0)
{
HandleRead(e.Buffer, 0, e.BytesTransferred);
if (!_handle.ReceiveAsync(e))
Process(null, e);
}
else
{
Disconnect();
}
break;
case SocketAsyncOperation.Send:
if (!Connected)
return;
_asyncOperation.Post(x => OnClientWrite(), null);
_sendIndex += e.BytesTransferred;
bool eos = (_sendIndex >= _sendBuffer.Length);
if (_sendQueue.Count == 0 && eos)
_processing[1] = false;
else
HandleSendQueue();
break;
}
}
else
{
if (e.LastOperation == SocketAsyncOperation.Connect)
_asyncOperation.Post(x => OnClientFail(), null);
Disconnect();
}
}
catch
{
Disconnect();
}
}