private void ReceiveCompleted(object sender, SocketAsyncEventArgs args) { if (args.SocketError == SocketError.Success && args.BytesTransferred > 0) { MemoryStream ms = args.UserToken as MemoryStream; ms.Write(args.Buffer, args.Offset, args.BytesTransferred); if (args.AcceptSocket.Available == 0) { ApartMessage(args.AcceptSocket, ms, 0); ms.Seek(0, SeekOrigin.Begin); ms.SetLength(0); } try { if (!args.AcceptSocket.ReceiveAsync(args)) { ReceiveCompleted(this, args); } } catch (NotSupportedException nse) { throw nse; } catch (ObjectDisposedException oe) { throw oe; } catch (SocketException se) { throw se; } catch (Exception e) { throw e; } } else { if (!args.AcceptSocket.SafeHandle.IsClosed) { if (ClientOff != null) { ClientOff.Invoke(this, args.AcceptSocket.RemoteEndPoint); } _clients.Remove(args.AcceptSocket); args.AcceptSocket.Shutdown(SocketShutdown.Both); args.AcceptSocket.Close(); } } }
private void CendCompleted(object sender, SocketAsyncEventArgs args) { if (args.SocketError == SocketError.Success && args.BytesTransferred > 0) { byte[] keyBytes = new byte[16]; Array.Copy(args.Buffer, 0, keyBytes, 0, 16); Guid key = new Guid(keyBytes); byte[] lenghtBytes = new byte[4]; Array.Copy(args.Buffer, 16, lenghtBytes, 0, 4); int length = BitConverter.ToInt32(lenghtBytes); byte[] msgBytes = new byte[length]; Array.Copy(args.Buffer, 20, msgBytes, 0, args.BytesTransferred - 20); SocketMessage msg = new SocketMessage { Key = key, Body = msgBytes, Length = length }; if (Sent != null) { Sent.Invoke(this, args.AcceptSocket, msg); } } else { if (!args.AcceptSocket.SafeHandle.IsClosed) { if (ClientOff != null) { ClientOff.Invoke(this, args.AcceptSocket.RemoteEndPoint); } _clients.Remove(args.AcceptSocket); args.AcceptSocket.Shutdown(SocketShutdown.Both); args.AcceptSocket.Close(); } } }
private void _OnReceive(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; System.Net.Sockets.Socket handler = state.workSocket ?? this._Socket; try { int bytes = handler.EndReceive(ar); ar.AsyncWaitHandle.Close(); if (bytes > 0) { DataReceived?.Invoke(state.workSocket, state.buffer, bytes); } else { switch (this._WorkingMode) { case SocketMode.Server: Clients.Remove(handler); ClientOff?.Invoke(handler); break; case SocketMode.Client: ClientOff?.Invoke(handler); break; default: break; } try { handler.Shutdown(SocketShutdown.Both); } catch (ObjectDisposedException ex) { if (ex.InnerException is SocketException) { throw ex; } } handler.Close(); return; } handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(_OnReceive), state); } catch (Exception ex) { if (ex is ObjectDisposedException) { return; } if (ex is SocketException) { Clients.Remove(handler); ClientOff?.Invoke(handler); return; } //C_Error.WriteErrorLog("DamperData", ex); throw; } }