public static void NotLoggedFile(string filePath, Socket socket, SocketAsyncOperation completedOperation) { if (IsEnabled) { Log.NotLoggedFile(filePath, GetHashCode(socket), completedOperation); } }
private static Task CreateTaskFromCompletionHandler(SocketAsyncEventArgs socketAsyncEventArgs, SocketAsyncOperation socketAsyncOperation) { TaskCompletionSource<string> completionSource = new TaskCompletionSource<string>(); socketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>((o, eventArgs) => { if (eventArgs.LastOperation == socketAsyncOperation) { if (eventArgs.SocketError == SocketError.Success) { completionSource.SetResult(""); } else { completionSource.SetException(new SocketException((int)eventArgs.SocketError)); } } }); return completionSource.Task; }
internal void StartOperationReceive() { this.m_CompletedOperation = SocketAsyncOperation.Receive; }
internal void StartOperationConnect() { this.m_CompletedOperation = SocketAsyncOperation.Connect; this.m_MultipleConnect = null; this.m_ConnectSocket = null; this.PinSocketAddressBuffer(); this.CheckPinNoBuffer(); }
internal void StartOperationSendTo() { this.m_CompletedOperation = SocketAsyncOperation.SendTo; this.PinSocketAddressBuffer(); }
private bool TryUnsafeSocketOperation(Socket socket, SocketAsyncOperation operation, SocketAsyncEventArgs socketAsyncEventArgs) { try { bool result = false; switch (operation) { case SocketAsyncOperation.Accept: result = socket.AcceptAsync(socketAsyncEventArgs); break; case SocketAsyncOperation.Send: result = socket.SendAsync(socketAsyncEventArgs); break; case SocketAsyncOperation.Receive: result = socket.ReceiveAsync(socketAsyncEventArgs); break; default: throw new InvalidOperationException("Unknown case called, should program something for this"); } if (!result) { OperationCallback(socket, socketAsyncEventArgs); } } catch (SocketException ex) { if (operation != SocketAsyncOperation.Accept) { HandleCommunicationError(socket, ex); } return false; } catch (ObjectDisposedException) { // If disposed, handle communication error was already done and we're just catching up on other threads. suppress it. return false; } return true; }
internal void StartOperationSendTo() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.SendTo; // WSASendTo uses a WSABuffer array describing buffers in which to // receive data and from which to send data respectively. Single and multiple buffers // are handled differently so as to optimize performance for the more common single buffer case. // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. // WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received. // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); }
internal void StartOperationDisconnect() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.Disconnect; CheckPinNoBuffer(); }
public TcpTransportResult(SocketAsyncOperation operation, Exception exception) { Operation = operation; Exception = exception; }
// Token: 0x0600007C RID: 124 RVA: 0x01028B40 File Offset: 0x01026D40 private void method_10(object sender, SocketAsyncEventArgs e) { try { if (e.SocketError == SocketError.Success) { SocketAsyncOperation lastOperation = e.LastOperation; if (lastOperation == SocketAsyncOperation.Connect) { this.ipendPoint_0 = (IPEndPoint)this.socket_0.RemoteEndPoint; this.bool_1 = true; this.socketAsyncEventArgs_0[0].SetBuffer(new byte[(int)this.ushort_0], 0, (int)this.ushort_0); this.asyncOperation_0.Post(new SendOrPostCallback(this.method_21), null); if (!this.socket_0.ReceiveAsync(e)) { this.method_10(null, e); } } else if (lastOperation == SocketAsyncOperation.Receive) { if (this.bool_1) { if (e.BytesTransferred == 0) { this.method_11(); } else { this.method_14(e.Buffer, 0, e.BytesTransferred); if (!this.socket_0.ReceiveAsync(e)) { this.method_10(null, e); } } } } else if (lastOperation == SocketAsyncOperation.Send) { if (this.bool_1) { bool flag = false; this.int_1 += e.BytesTransferred; this.asyncOperation_0.Post(new SendOrPostCallback(this.method_16), new object[] { this.int_1 / this.byte_0.Length * 100, this.int_1, this.byte_0.Length }); if (this.int_1 >= this.byte_0.Length) { flag = true; this.asyncOperation_0.Post(new SendOrPostCallback(this.method_22), this.byte_0.Length - 4); } if (this.queue_0.Count == 0 && flag) { this.bool_2[1] = false; } else { this.method_13(); } } } } else { this.asyncOperation_0.Post(new SendOrPostCallback(this.method_23), new SocketException((int)e.SocketError)); this.method_11(); } } catch (Exception arg) { this.asyncOperation_0.Post(new SendOrPostCallback(this.method_24), arg); this.method_11(); } }
//////////////////////////////////////////////////////////////////////////// // Inner Process... protected void IoComplete(object sender, SocketAsyncEventArgs args) { try { SocketError err = args.SocketError; byte[] rcb = args.Buffer; // buffer int rcn = args.BytesTransferred; // buffer length SocketAsyncOperation opc = args.LastOperation; if (SocketAsyncOperation.Receive == opc) { // close message from server if (err != SocketError.Success || 0 == rcn) { Console.WriteLine("IoComplete::Disconnected"); CloseSocket(); return; } lock (m_oLock) { // DeCryption int lenD = 0; PGN.Util.DeCrypt(ref m_rcvB, ref lenD, rcb, rcn); // DeCoding PGN.Packet pck = new PGN.Packet(ref m_rcvB, lenD); // data buffer and length byte[] b = pck.DataBuf; int l = pck.DataLen; // read the key and id from string if (0 > m_aId) { int n = 0; int cnt = 0; n = Array.FindIndex(b, 0, _s => _s == (byte)' '); cnt = l - (n + 1); string s_uid = Encoding.Default .GetString(b, 0, n) .Trim(); m_aId = System.Convert.ToInt32(s_uid); string s_key = null; Array.Copy(b, n + 1, m_vCrp, 0, cnt); s_key = Encoding.Default.GetString(m_vCrp, 0, cnt).Trim(); Console.WriteLine("Auth Uid::{0} , Key:{1}", m_aId, s_key); } // the transformed stream exists else { string s_chat = Encoding.Default .GetString(b, 0, l).Trim(); Console.WriteLine(s_chat); int op = PGN.NTC.OP_CHAT; this.Send("server send::" + s_chat, op); } } m_scH.ReceiveAsync(m_arRcv); return; } else if (SocketAsyncOperation.Connect == opc) { if (err != SocketError.Success) { Console.WriteLine("IoComplete::Cann't Connect to Server"); CloseSocket(); } else { Console.WriteLine("IoComplete::Connection Success"); m_scH.ReceiveAsync(m_arRcv); // enable the receive event } m_arCon = null; // release the connection event instance return; } else if (SocketAsyncOperation.Send == opc) { if (err != SocketError.Success) { Console.WriteLine("IoComplete::Cann't Send to Server"); CloseSocket(); return; } lock (m_oLock) { m_sndC = 0; } Console.WriteLine("IoComplete::Send complete"); return; } } catch (SocketException) { Console.WriteLine("IoComplete::SocketException"); } catch (Exception) { Console.WriteLine("IoComplete::Exception"); } }
/// <summary> /// 提供一个错误,初始化一个 <see cref="ExceptionEventArgs "/> 类的新实例。 /// </summary> /// <param name="exception">一个错误。</param> public SocketExceptionEventArgs(SocketAsyncOperation lastOperation, Exception exception) : base(exception) { this.LastOperation = lastOperation; }
private static Task CreateTaskFromCompletionHandler(SocketAsyncEventArgs socketAsyncEventArgs, SocketAsyncOperation socketAsyncOperation) { TaskCompletionSource <string> completionSource = new TaskCompletionSource <string>(); socketAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>((o, eventArgs) => { if (eventArgs.LastOperation == socketAsyncOperation) { if (eventArgs.SocketError == SocketError.Success) { completionSource.SetResult(""); } else { completionSource.SetException(new SocketException((int)eventArgs.SocketError)); } } }); return(completionSource.Task); }
public SocketReceiveErrorEventArgs(int errorCode, SocketAsyncOperation lastOperation) { _errorCode = errorCode; _lastOperation = lastOperation; }
public ServerConnectEventArgs(SocketAsyncOperation operation) { this.operation = operation; }
internal unsafe void StartOperationReceiveMessageFrom() { this.m_CompletedOperation = SocketAsyncOperation.ReceiveMessageFrom; this.PinSocketAddressBuffer(); if (this.m_WSAMessageBuffer == null) { this.m_WSAMessageBuffer = new byte[s_WSAMsgSize]; this.m_WSAMessageBufferGCHandle = GCHandle.Alloc(this.m_WSAMessageBuffer, GCHandleType.Pinned); this.m_PtrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSAMessageBuffer, 0); } bool flag = this.m_CurrentSocket.AddressFamily == AddressFamily.InterNetwork; bool flag2 = this.m_CurrentSocket.AddressFamily == AddressFamily.InterNetworkV6; if (flag && ((this.m_ControlBuffer == null) || (this.m_ControlBuffer.Length != s_ControlDataSize))) { if (this.m_ControlBufferGCHandle.IsAllocated) { this.m_ControlBufferGCHandle.Free(); } this.m_ControlBuffer = new byte[s_ControlDataSize]; } else if (flag2 && ((this.m_ControlBuffer == null) || (this.m_ControlBuffer.Length != s_ControlDataIPv6Size))) { if (this.m_ControlBufferGCHandle.IsAllocated) { this.m_ControlBufferGCHandle.Free(); } this.m_ControlBuffer = new byte[s_ControlDataIPv6Size]; } if (!this.m_ControlBufferGCHandle.IsAllocated) { this.m_ControlBufferGCHandle = GCHandle.Alloc(this.m_ControlBuffer, GCHandleType.Pinned); this.m_PtrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_ControlBuffer, 0); } if (this.m_Buffer != null) { if (this.m_WSARecvMsgWSABufferArray == null) { this.m_WSARecvMsgWSABufferArray = new WSABuffer[1]; } this.m_WSARecvMsgWSABufferArray[0].Pointer = this.m_PtrSingleBuffer; this.m_WSARecvMsgWSABufferArray[0].Length = this.m_Count; this.m_WSARecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(this.m_WSARecvMsgWSABufferArray, GCHandleType.Pinned); this.m_PtrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSARecvMsgWSABufferArray, 0); } else { this.m_WSARecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(this.m_WSABufferArray, GCHandleType.Pinned); this.m_PtrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSABufferArray, 0); } UnsafeNclNativeMethods.OSSOCK.WSAMsg* ptrWSAMessageBuffer = (UnsafeNclNativeMethods.OSSOCK.WSAMsg*) this.m_PtrWSAMessageBuffer; ptrWSAMessageBuffer->socketAddress = this.m_PtrSocketAddressBuffer; ptrWSAMessageBuffer->addressLength = (uint) this.m_SocketAddress.Size; ptrWSAMessageBuffer->buffers = this.m_PtrWSARecvMsgWSABufferArray; if (this.m_Buffer != null) { ptrWSAMessageBuffer->count = 1; } else { ptrWSAMessageBuffer->count = (uint) this.m_WSABufferArray.Length; } if (this.m_ControlBuffer != null) { ptrWSAMessageBuffer->controlBuffer.Pointer = this.m_PtrControlBuffer; ptrWSAMessageBuffer->controlBuffer.Length = this.m_ControlBuffer.Length; } ptrWSAMessageBuffer->flags = this.m_SocketFlags; }
internal void SetLastOperation (SocketAsyncOperation op) { if (disposed) throw new ObjectDisposedException ("System.Net.Sockets.SocketAsyncEventArgs"); if (Interlocked.Exchange (ref in_progress, 1) != 0) throw new InvalidOperationException ("Operation already in progress"); LastOperation = op; }
public SocketArgs(SocketAsyncOperation operation) { Operation = operation; }
internal void StartOperationConnect() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.Connect; m_MultipleConnect = null; m_ConnectSocket = null; // ConnectEx uses a sockaddr buffer containing he remote address to which to connect. // It can also optionally take a single buffer of data to send after the connection is complete. // // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. // The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin. PinSocketAddressBuffer(); CheckPinNoBuffer(); }
private void DoAsync(SocketAsyncOperation OperationIdentifier, Func <SocketAsyncEventArgs, Boolean> Operation, Func <SocketAsyncEventArgs, Action> ResultToCompleted, Action <Exception> Faulted) { var Context = new AsyncOperationContext(); if (!TryLockAsyncOperation(OperationIdentifier, Context)) { Context.Dispose(); Faulted(new SocketException((int)(SocketError.Shutdown))); return; } var Success = false; try { Context.ResultToCompleted = ResultToCompleted; Context.Faulted = Faulted; var TimeoutSeconds = this.TimeoutSeconds; if (TimeoutSeconds.HasValue) { var IsCompleted = new LockedVariable <Boolean>(false); var Timer = new Timer(o => { if (!IsCompleted.Check(b => b)) { if (TimedOut != null) { TimedOut(); } } }, null, TimeoutSeconds.Value * 1000, Timeout.Infinite); Context.ReleaseAsyncOperation = () => { IsCompleted.Update(b => true); if (Timer != null) { Timer.Dispose(); Timer = null; } ReleaseAsyncOperation(OperationIdentifier); }; } else { Context.ReleaseAsyncOperation = () => ReleaseAsyncOperation(OperationIdentifier); } Success = true; } finally { if (!Success) { ReleaseAsyncOperation(OperationIdentifier); } } Success = false; Exception Exception = null; try { bool willRaiseEvent = Operation(Context.EventArgs); if (!willRaiseEvent) { QueueUserWorkItem(Context.DoOnCompletion); } Success = true; } catch (ObjectDisposedException) { Exception = new SocketException((int)(SocketError.OperationAborted)); } finally { if (!Success) { Context.ReleaseAsyncOperation(); } } if (Exception != null) { Faulted(Exception); } }
internal void StartOperationSend() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.Send; // WSASend uses a WSABuffer array describing buffers of data to send. // Single and multiple buffers are handled differently so as to optimize // performance for the more common single buffer case. // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. }
public void Increment(SocketAsyncOperation operation, SocketError?error = null) { var success = error.HasValue && error.Value == SocketError.Success; switch (operation) { case SocketAsyncOperation.Accept: if (!error.HasValue) { Interlocked.Increment(ref Accept); } else if (success) { Interlocked.Increment(ref AcceptSuccess); } else { Interlocked.Increment(ref AcceptFailure); } break; case SocketAsyncOperation.Connect: if (!error.HasValue) { Interlocked.Increment(ref Connect); } else if (success) { Interlocked.Increment(ref ConnectSuccess); } else { Interlocked.Increment(ref ConnectFailure); } break; case SocketAsyncOperation.Disconnect: if (!error.HasValue) { Interlocked.Increment(ref Disconnect); } else if (success) { Interlocked.Increment(ref DisconnectSuccess); } else { Interlocked.Increment(ref DisconnectFailure); } break; case SocketAsyncOperation.Receive: if (!error.HasValue) { Interlocked.Increment(ref Receive); } else if (success) { Interlocked.Increment(ref ReceiveSuccess); } else { Interlocked.Increment(ref ReceiveFailure); } break; case SocketAsyncOperation.ReceiveFrom: if (!error.HasValue) { Interlocked.Increment(ref ReceiveFrom); } else if (success) { Interlocked.Increment(ref ReceiveFromSuccess); } else { Interlocked.Increment(ref ReceiveFromFailure); } break; case SocketAsyncOperation.ReceiveMessageFrom: if (!error.HasValue) { Interlocked.Increment(ref ReceiveMessageFrom); } else if (success) { Interlocked.Increment(ref ReceiveMessageFromSuccess); } else { Interlocked.Increment(ref ReceiveMessageFromFailure); } break; case SocketAsyncOperation.Send: if (!error.HasValue) { Interlocked.Increment(ref Send); } else if (success) { Interlocked.Increment(ref SendSuccess); } else { Interlocked.Increment(ref SendFailure); } break; case SocketAsyncOperation.SendPackets: if (!error.HasValue) { Interlocked.Increment(ref SendPackets); } else if (success) { Interlocked.Increment(ref SendPacketsSuccess); } else { Interlocked.Increment(ref SendPacketsFailure); } break; case SocketAsyncOperation.SendTo: if (!error.HasValue) { Interlocked.Increment(ref SendTo); } else if (success) { Interlocked.Increment(ref SendToSuccess); } else { Interlocked.Increment(ref SendToFailure); } break; default: break; } }
internal void StartOperationReceiveMessageFrom() { // Remember the operation type. _completedOperation = SocketAsyncOperation.ReceiveMessageFrom; InnerStartOperationReceiveMessageFrom(); }
private bool ValidateCompletedEvent(SocketAsyncEventArgs e, SocketAsyncOperation expected) { if (_error != null) return false; if (e.SocketError != SocketError.Success) { SetError(e.SocketError); return false; } if (e.LastOperation != expected) { SetError(new InvalidOperationException(string.Format( "Excepted last operation {0} but last operation was {1}.", expected, e.LastOperation))); return false; } return true; }
public static void NotLoggedFile(string filePath, Socket socket, SocketAsyncOperation completedOperation) => Log.NotLoggedFile(filePath, GetHashCode(socket), completedOperation);
internal void SetLastOperation (SocketAsyncOperation op) { LastOperation = op; }
internal void StartOperationAccept() { this.m_CompletedOperation = SocketAsyncOperation.Accept; this.m_AcceptAddressBufferCount = 2 * (this.m_CurrentSocket.m_RightEndPoint.Serialize().Size + 0x10); if (this.m_Buffer != null) { if (this.m_Count < this.m_AcceptAddressBufferCount) { throw new ArgumentException(SR.GetString("net_buffercounttoosmall", new object[] { "Count" })); } } else { if ((this.m_AcceptBuffer == null) || (this.m_AcceptBuffer.Length < this.m_AcceptAddressBufferCount)) { this.m_AcceptBuffer = new byte[this.m_AcceptAddressBufferCount]; } this.CheckPinSingleBuffer(false); } }
internal void DoOperation (SocketAsyncOperation operation, Socket socket) { ThreadStart callback = null; curSocket = socket; switch (operation) { case SocketAsyncOperation.Connect: #if MOONLIGHT socket.seed_endpoint = RemoteEndPoint; #endif callback = new ThreadStart (ConnectCallback); SocketError = SocketError.Success; LastOperation = operation; break; default: throw new NotSupportedException (); } Thread t = new Thread (callback); t.IsBackground = true; t.Start (); }
internal void StartOperationDisconnect() { this.m_CompletedOperation = SocketAsyncOperation.Disconnect; this.CheckPinNoBuffer(); }
public void Register(IActorRef connection, SocketAsyncOperation? initialOps) { _connection = connection; }
internal void StartOperationReceiveFrom() { this.m_CompletedOperation = SocketAsyncOperation.ReceiveFrom; this.PinSocketAddressBuffer(); }
internal void CloseConnection(SocketError err, SocketAsyncOperation operation) { string msg = $"A socket error occured while trying to {operation}: {err}"; parent.CloseInternal(ConnectionCloseReason.SocketError, msg, null); }
internal void SetLastOperation(SocketAsyncOperation op) { LastOperation = op; }
private void NotLoggedFile(string filePath, int socketHash, SocketAsyncOperation completedOperation) { WriteEvent(NotLoggedFileId, filePath, socketHash, (int)completedOperation); }
public TcpTransportResult(SocketAsyncOperation operation, SocketError error) { Operation = operation; Error = error; }
internal void StartOperationConnect() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Connect; _multipleConnect = null; _connectSocket = null; InnerStartOperationConnect(); }
internal void StartOperationAccept() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.Accept; // AcceptEx needs a single buffer with room for two special sockaddr data structures. // It can also take additional buffer space in front of those special sockaddr // structures that can be filled in with initial data coming in on a connection. // First calculate the special AcceptEx address buffer size. // It is the size of two native sockaddr buffers with 16 extra bytes each. // The native sockaddr buffers vary by address family so must reference the current socket. m_AcceptAddressBufferCount = 2 * (m_CurrentSocket.m_RightEndPoint.Serialize().Size + 16); // If our caller specified a buffer (willing to get received data with the Accept) then // it needs to be large enough for the two special sockaddr buffers that AcceptEx requires. // Throw if that buffer is not large enough. if(m_Buffer != null) { // Caller specified a buffer - see if it is large enough if(m_Count < m_AcceptAddressBufferCount) { throw new ArgumentException(SR.GetString(SR.net_buffercounttoosmall, "Count")); } // Buffer is already pinned. } else { // Caller didn't specify a buffer so use an internal one. // See if current internal one is big enough, otherwise create a new one. if(m_AcceptBuffer == null || m_AcceptBuffer.Length < m_AcceptAddressBufferCount) { m_AcceptBuffer = new byte[m_AcceptAddressBufferCount]; } CheckPinSingleBuffer(false); } }
internal void StartOperationDisconnect() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Disconnect; InnerStartOperationDisconnect(); }
internal void StartOperationWrapperConnect(MultipleConnectAsync args) { m_CompletedOperation = SocketAsyncOperation.Connect; m_MultipleConnect = args; m_ConnectSocket = null; }
internal void StartOperationReceiveMessageFrom() { // Remember the operation type. _completedOperation = SocketAsyncOperation.ReceiveMessageFrom; InnerStartOperationReceiveMessageFrom(); }
internal void StartOperationReceiveMessageFrom() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.ReceiveMessageFrom; // WSARecvMsg uses a WSAMsg descriptor. // The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a sockaddr. // The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a WSABuffer array describing data buffers. // WSAMsg also contains a single WSABuffer describing a control buffer. // PinSocketAddressBuffer(); // Create and pin a WSAMessageBuffer if none already. if(m_WSAMessageBuffer == null) { m_WSAMessageBuffer = new byte[s_WSAMsgSize]; m_WSAMessageBufferGCHandle = GCHandle.Alloc(m_WSAMessageBuffer, GCHandleType.Pinned); m_PtrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(m_WSAMessageBuffer, 0); } // Create and pin an appropriately sized control buffer if none already IPAddress ipAddress = (m_SocketAddress.Family == AddressFamily.InterNetworkV6 ? m_SocketAddress.GetIPAddress() : null); bool ipv4 = (m_CurrentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode bool ipv6 = m_CurrentSocket.AddressFamily == AddressFamily.InterNetworkV6; if(ipv4 && (m_ControlBuffer == null || m_ControlBuffer.Length != s_ControlDataSize)) { if(m_ControlBufferGCHandle.IsAllocated) { m_ControlBufferGCHandle.Free(); } m_ControlBuffer = new byte[s_ControlDataSize]; } else if(ipv6 && (m_ControlBuffer == null || m_ControlBuffer.Length != s_ControlDataIPv6Size)) { if(m_ControlBufferGCHandle.IsAllocated) { m_ControlBufferGCHandle.Free(); } m_ControlBuffer = new byte[s_ControlDataIPv6Size]; } if(!m_ControlBufferGCHandle.IsAllocated) { m_ControlBufferGCHandle = GCHandle.Alloc(m_ControlBuffer, GCHandleType.Pinned); m_PtrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(m_ControlBuffer, 0); } // If single buffer we need a pinned 1 element WSABuffer. if(m_Buffer != null) { if(m_WSARecvMsgWSABufferArray == null) { m_WSARecvMsgWSABufferArray = new WSABuffer[1]; } m_WSARecvMsgWSABufferArray[0].Pointer = m_PtrSingleBuffer; m_WSARecvMsgWSABufferArray[0].Length = m_Count; m_WSARecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(m_WSARecvMsgWSABufferArray, GCHandleType.Pinned); m_PtrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(m_WSARecvMsgWSABufferArray, 0); } else { // just pin the multi-buffer WSABuffer m_WSARecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(m_WSABufferArray, GCHandleType.Pinned); m_PtrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(m_WSABufferArray, 0); } // Fill in WSAMessageBuffer unsafe { UnsafeNclNativeMethods.OSSOCK.WSAMsg* pMessage = (UnsafeNclNativeMethods.OSSOCK.WSAMsg*)m_PtrWSAMessageBuffer;; pMessage->socketAddress = m_PtrSocketAddressBuffer; pMessage->addressLength = (uint)m_SocketAddress.Size; pMessage->buffers = m_PtrWSARecvMsgWSABufferArray; if(m_Buffer != null) { pMessage->count = (uint)1; } else { pMessage->count = (uint)m_WSABufferArray.Length; } if(m_ControlBuffer != null) { pMessage->controlBuffer.Pointer = m_PtrControlBuffer; pMessage->controlBuffer.Length = m_ControlBuffer.Length; } pMessage->flags = m_SocketFlags; } }
internal void StartOperationSendTo() { // Remember the operation type. _completedOperation = SocketAsyncOperation.SendTo; InnerStartOperationSendTo(); }
internal void StartOperationSendPackets() { // Remember the operation type. m_CompletedOperation = SocketAsyncOperation.SendPackets; // Prevent mutithreaded manipulation of the list. if (m_SendPacketsElements != null) { m_SendPacketsElementsInternal = (SendPacketsElement[])m_SendPacketsElements.Clone(); } // TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as // descriptors for buffers and files to be sent. It also takes a send size // and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle. // This function basically opens the files to get the file handles, pins down any buffers // specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed // to TransmitPackets. // Scan the elements to count files and buffers m_SendPacketsElementsFileCount = 0; m_SendPacketsElementsBufferCount = 0; foreach (SendPacketsElement spe in m_SendPacketsElementsInternal) { if(spe != null) { if(spe.m_FilePath != null) { m_SendPacketsElementsFileCount++; } if(spe.m_Buffer != null && spe.m_Count > 0) { m_SendPacketsElementsBufferCount++; } } } // Attempt to open the files if any if(m_SendPacketsElementsFileCount > 0) { // Create arrays for streams and handles m_SendPacketsFileStreams = new FileStream[m_SendPacketsElementsFileCount]; m_SendPacketsFileHandles = new SafeHandle[m_SendPacketsElementsFileCount]; // Loop through the elements attempting to open each files and get its handle int index = 0; foreach(SendPacketsElement spe in m_SendPacketsElementsInternal) { if(spe != null && spe.m_FilePath != null) { Exception fileStreamException = null; try { // Create a FileStream to open the file m_SendPacketsFileStreams[index] = new FileStream(spe.m_FilePath,FileMode.Open,FileAccess.Read,FileShare.Read); } catch (Exception ex) { // Save the exception to throw after closing any previous successful file opens fileStreamException = ex; } if (fileStreamException != null) { // Got exception opening a file - do some cleanup then throw for(int i = 0; i < m_SendPacketsElementsFileCount; i++) { // Dereference handles m_SendPacketsFileHandles[i] = null; // Close any open streams if(m_SendPacketsFileStreams[i] != null) { m_SendPacketsFileStreams[i].Close(); m_SendPacketsFileStreams[i] = null; } } throw fileStreamException; } // Get the file handle from the stream ExceptionHelper.UnmanagedPermission.Assert(); try { m_SendPacketsFileHandles[index] = m_SendPacketsFileStreams[index].SafeFileHandle; } finally { SecurityPermission.RevertAssert(); } index++; } } } CheckPinSendPackets(); }
internal void StartOperationDisconnect() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Disconnect; InnerStartOperationDisconnect(); }
internal void StartOperationWrapperConnect(MultipleConnectAsync args) { _completedOperation = SocketAsyncOperation.Connect; _multipleConnect = args; _connectSocket = null; }
internal void StartOperationSend() { this.m_CompletedOperation = SocketAsyncOperation.Send; }
internal void StartOperationSend() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Send; InnerStartOperationSend(); }
internal void StartOperationSendPackets() { this.m_CompletedOperation = SocketAsyncOperation.SendPackets; if (this.m_SendPacketsElements != null) { this.m_SendPacketsElementsInternal = (SendPacketsElement[]) this.m_SendPacketsElements.Clone(); } this.m_SendPacketsElementsFileCount = 0; this.m_SendPacketsElementsBufferCount = 0; foreach (SendPacketsElement element in this.m_SendPacketsElementsInternal) { if (element != null) { if ((element.m_FilePath != null) && (element.m_FilePath.Length > 0)) { this.m_SendPacketsElementsFileCount++; } if (element.m_Buffer != null) { this.m_SendPacketsElementsBufferCount++; } } } if (this.m_SendPacketsElementsFileCount > 0) { this.m_SendPacketsFileStreams = new FileStream[this.m_SendPacketsElementsFileCount]; this.m_SendPacketsFileHandles = new SafeHandle[this.m_SendPacketsElementsFileCount]; int index = 0; foreach (SendPacketsElement element2 in this.m_SendPacketsElementsInternal) { if (((element2 != null) && (element2.m_FilePath != null)) && (element2.m_FilePath.Length > 0)) { Exception exception = null; try { this.m_SendPacketsFileStreams[index] = new FileStream(element2.m_FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception exception2) { exception = exception2; } if (exception != null) { for (int i = 0; i < this.m_SendPacketsElementsFileCount; i++) { this.m_SendPacketsFileHandles[i] = null; if (this.m_SendPacketsFileStreams[i] != null) { this.m_SendPacketsFileStreams[i].Close(); this.m_SendPacketsFileStreams[i] = null; } } throw exception; } ExceptionHelper.UnmanagedPermission.Assert(); try { this.m_SendPacketsFileHandles[index] = this.m_SendPacketsFileStreams[index].SafeFileHandle; } finally { CodeAccessPermission.RevertAssert(); } index++; } } } this.CheckPinSendPackets(); }
/// <summary> /// Raise error handler for specified socket level error. /// </summary> /// <param name="operation">Last operation.</param> /// <param name="messageId">ID of message.</param> /// <param name="error">Socket error.</param> /// <exception cref="SocketException"> /// There are no event handlers registered. /// </exception> protected void HandleError( SocketAsyncOperation operation, int messageId, SocketError error ) { if ( error == System.Net.Sockets.SocketError.Success ) { return; } if ( !this.OnTransportError( new RpcTransportErrorEventArgs( operation, messageId, error ) ) ) { throw new SocketException( ( int )error ); } }
//////////////////////////////////////////////////////////////////////////// // Inner Process... protected void IoComplete(object sender, SocketAsyncEventArgs args) { try { SocketError err = args.SocketError; int rcn = args.BytesTransferred; byte[] rcb = args.Buffer; SocketAsyncOperation opc = args.LastOperation; if (SocketAsyncOperation.Receive == opc) { // close message from server if (err != SocketError.Success || 0 == rcn) { Console.WriteLine("IoComplete::Disconnect by server"); CloseSocket(); return; } lock (m_lock) { // read the key and id from string if (-1 == m_autId) { int n = 0; string rcv_s = Encoding.Default.GetString(rcb).Trim(); m_autKey = new byte[PGN.PCK_KEY + 4]; Array.Clear(m_autKey, 0, PGN.PCK_KEY + 4); m_autId = 0; for (n = 0; n < PGN.PCK_KEY; ++n) { m_autKey[n] = (byte)rcv_s[n]; } string skey = Encoding.Default.GetString(m_autKey).Trim(); string sid = rcv_s.Substring(32).Trim(); m_autId = Convert.ToInt32(sid); string ss = Encoding.Default.GetString(m_autKey).Trim(); Console.WriteLine("Auth Key::" + skey + ", Id:" + m_autId); } // the transformed stream exists else { ReadBuf(args.Buffer, rcn); } } m_scH.ReceiveAsync(m_arRcv); return; } else if (SocketAsyncOperation.Connect == opc) { if (err != SocketError.Success) { Console.WriteLine("IoComplete::Cann't Connect to Server"); CloseSocket(); } else { Console.WriteLine("IoComplete::Connection Success"); m_scH.ReceiveAsync(m_arRcv); // enable the receive event } m_arCon = null; // release the connection event instance return; } else if (SocketAsyncOperation.Send == opc) { if (err != SocketError.Success) { Console.WriteLine("IoComplete::Cann't Send to Server"); CloseSocket(); return; } lock (m_lock) { m_bSnd = 0; } Console.WriteLine("IoComplete::Send compelte"); return; } } catch (SocketException) { } catch (Exception) { } }