/// <summary> /// Initiates a read operation from a bulk IN endpoint. /// To enable reading without blocking the main thread, uses an asynchronous delegate. /// </summary> /// /// <remarks> /// To enable reading more than 64 bytes (with device firmware support), increase bytesToRead. /// </remarks> public static void ReadBulkData() { if (DeviceDetected) { const uint bytesToRead = BulkBufferSize; // CH1+CH2+CHD+frame number // Define a delegate for the ReadViaBulkTransfer method of WinUsbDevice. ReadFromDeviceDelegate myReadFromDeviceDelegate = _usbDevice.ReadViaBulkTransfer; // The BeginInvoke method calls MyWinUsbDevice.ReadViaBulkTransfer to attempt // to read data. The method has the same parameters as ReadViaBulkTransfer, // plus two additional parameters: // GetReceivedBulkData is the callback routine that executes when // ReadViaBulkTransfer returns. // MyReadFromDeviceDelegate is the asynchronous delegate object. var readState = new AsyncReadState { Success = false, BytesRead = 0, Data = new byte[BulkBufferSize] }; myReadFromDeviceDelegate.BeginInvoke( Convert.ToByte(_usbDevice.DeviceInfo.BulkInPipe), bytesToRead, ref readState.Data, ref readState.BytesRead, out readState.Success, GetReceivedBulkData, readState ); } }
/// <summary>Start monitoring the current directory.</summary> private void StartRaisingEvents() { // If we're called when "Initializing" is true, set enabled to true if (IsSuspended()) { _enabled = true; return; } // If we're already running, don't do anything. if (!IsHandleInvalid(_directoryHandle)) { return; } // Create handle to directory being monitored var defaultSecAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); _directoryHandle = Interop.Kernel32.CreateFile( lpFileName: _directory, dwDesiredAccess: Interop.Kernel32.FileOperations.FILE_LIST_DIRECTORY, dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write, securityAttrs: ref defaultSecAttrs, dwCreationDisposition: FileMode.Open, dwFlagsAndAttributes: Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS | Interop.Kernel32.FileOperations.FILE_FLAG_OVERLAPPED, hTemplateFile: IntPtr.Zero); if (IsHandleInvalid(_directoryHandle)) { _directoryHandle = null; throw new FileNotFoundException(SR.Format(SR.FSW_IOError, _directory)); } // Create the state associated with the operation of monitoring the direction AsyncReadState state; try { // Start ignoring all events that were initiated before this, and // allocate the buffer to be pinned and used for the duration of the operation int session = Interlocked.Increment(ref _currentSession); byte[] buffer = AllocateBuffer(); // Store all state, including a preallocated overlapped, into the state object that'll be // passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned // from now until the end of the operation. state = new AsyncReadState(session, buffer, _directoryHandle, ThreadPoolBoundHandle.BindHandle(_directoryHandle)); unsafe { state.PreAllocatedOverlapped = new PreAllocatedOverlapped(ReadDirectoryChangesCallback, state, buffer); } } catch { // Make sure we don't leave a valid directory handle set if we're not running _directoryHandle.Dispose(); _directoryHandle = null; throw; } // Start monitoring _enabled = true; Monitor(state); }
/// <summary>Start monitoring the current directory.</summary> private void StartRaisingEvents() { // If we're called when "Initializing" is true, set enabled to true if (IsSuspended()) { _enabled = true; return; } // If we're already running, don't do anything. if (!IsHandleInvalid(_directoryHandle)) return; // Create handle to directory being monitored var defaultSecAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); _directoryHandle = Interop.Kernel32.CreateFile( lpFileName: _directory, dwDesiredAccess: Interop.Kernel32.FileOperations.FILE_LIST_DIRECTORY, dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write, securityAttrs: ref defaultSecAttrs, dwCreationDisposition: FileMode.Open, dwFlagsAndAttributes: Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS | Interop.Kernel32.FileOperations.FILE_FLAG_OVERLAPPED, hTemplateFile: IntPtr.Zero); if (IsHandleInvalid(_directoryHandle)) { _directoryHandle = null; throw new FileNotFoundException(SR.Format(SR.FSW_IOError, _directory)); } // Create the state associated with the operation of monitoring the direction AsyncReadState state; try { // Start ignoring all events that were initiated before this, and // allocate the buffer to be pinned and used for the duration of the operation int session = Interlocked.Increment(ref _currentSession); byte[] buffer = AllocateBuffer(); // Store all state, including a preallocated overlapped, into the state object that'll be // passed from iteration to iteration during the lifetime of the operation. The buffer will be pinned // from now until the end of the operation. state = new AsyncReadState(session, buffer, _directoryHandle, ThreadPoolBoundHandle.BindHandle(_directoryHandle)); unsafe { state.PreAllocatedOverlapped = new PreAllocatedOverlapped(ReadDirectoryChangesCallback, state, buffer); } } catch { // Make sure we don't leave a valid directory handle set if we're not running _directoryHandle.Dispose(); _directoryHandle = null; throw; } // Start monitoring _enabled = true; Monitor(state); }
/// <summary>Callback invoked when an asynchronous read on the directory handle completes.</summary> private unsafe void ReadDirectoryChangesCallback(uint errorCode, uint numBytes, NativeOverlapped *overlappedPointer) { AsyncReadState state = (AsyncReadState)ThreadPoolBoundHandle.GetNativeOverlappedState(overlappedPointer); try { if (IsHandleInvalid(state.DirectoryHandle)) { return; } if (errorCode != 0) { // Inside a service the first completion status is false; // need to monitor again. const int ERROR_OPERATION_ABORTED = 995; if (errorCode != ERROR_OPERATION_ABORTED) { OnError(new ErrorEventArgs(new Win32Exception((int)errorCode))); EnableRaisingEvents = false; } return; } // Ignore any events that occurred before this "session", // so we don't get changed or error events after we // told FSW to stop. Even with this check, though, there's a small // race condition, as immediately after we do the check, raising // events could be disabled. if (state.Session != Volatile.Read(ref _currentSession)) { return; } if (numBytes == 0) { NotifyInternalBufferOverflowEvent(); } else { ParseEventBufferAndNotifyForEach(state.Buffer); } } finally { // Clean up state associated with this one iteration state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); // Then call Monitor again to either start the next iteration or // clean up the whole operation. Monitor(state); } }
private void AsyncEndRead(IAsyncResult asyncResult) { AsyncReadState asyncState = (AsyncReadState)asyncResult.AsyncState; BaseAsyncResult.PerRequest pereq = asyncState.Pereq; int count = 0; try { this.CompleteCheck(pereq, InternalError.InvalidEndReadCompleted); pereq.SetRequestCompletedSynchronously(asyncResult.CompletedSynchronously); BaseAsyncResult.EqualRefCheck(base.perRequest, pereq, InternalError.InvalidEndRead); Stream stream = Util.NullCheck <Stream>(pereq.ResponseStream, InternalError.InvalidEndReadStream); count = stream.EndRead(asyncResult); if (0 < count) { Util.NullCheck <Stream>(this.ResponseStream, InternalError.InvalidEndReadCopy).Write(this.buildBatchBuffer, 0, count); asyncState.TotalByteCopied += count; if (!asyncResult.CompletedSynchronously && stream.CanRead) { do { asyncResult = BaseAsyncResult.InvokeAsync(new BaseAsyncResult.AsyncAction(stream.BeginRead), this.buildBatchBuffer, 0, this.buildBatchBuffer.Length, new AsyncCallback(this.AsyncEndRead), asyncState); pereq.SetRequestCompletedSynchronously(asyncResult.CompletedSynchronously); if ((!asyncResult.CompletedSynchronously || pereq.RequestCompleted) || base.IsCompletedInternally) { return; } }while (stream.CanRead); } } else { pereq.SetComplete(); if (!base.IsCompletedInternally && !pereq.RequestCompletedSynchronously) { this.FinishCurrentChange(pereq); } } } catch (Exception exception) { if (base.HandleFailure(pereq, exception)) { throw; } } finally { this.HandleCompleted(pereq); } }
/// <summary> /// Start reading asynchronously from the controller /// </summary> private AsyncReadState BeginAsyncRead(AsyncReadState state) { lock (ioLock) { // if the stream is valid and ready if (device.Stream != null && device.Stream.CanRead) { // setup the read and the callback state.NewBuffer(); readStates.Add(device.Stream.BeginRead(state.Buffer, 0, state.Length, OnReadData, state)); return(state); } } throw new OperationCanceledException(); }
/// <summary> /// Start reading asynchronously from the controller /// </summary> private AsyncReadState BeginAsyncRead() { lock (ioLock) { Debug.WriteLine("Read Start"); // if the stream is valid and ready if (device.Stream != null && device.Stream.CanRead) { // setup the read and the callback AsyncReadState state = new AsyncReadState(false); readStates.Add(device.Stream.BeginRead(state.Buffer, 0, state.Length, OnReadData, state)); Debug.WriteLine($"Read Threads: {ReadThreads}"); return(state); } } throw new OperationCanceledException(); }
/// <summary> /// Initiates the next asynchronous read operation if monitoring is still desired. /// If the directory handle has been closed due to an error or due to event monitoring /// being disabled, this cleans up state associated with the operation. /// </summary> private unsafe void Monitor(AsyncReadState state) { // This method should only ever access the directory handle via the state object passed in, and not access it // via _directoryHandle. While this function is executing asynchronously, another thread could set // EnableRaisingEvents to false and then back to true, restarting the FSW and causing a new directory handle // and thread pool binding to be stored. This function could then get into an inconsistent state by doing some // operations against the old handles and some against the new. NativeOverlapped *overlappedPointer = null; bool continueExecuting = false; try { // If shutdown has been requested, exit. The finally block will handle // cleaning up the entire operation, as continueExecuting will remain false. if (!_enabled || IsHandleInvalid(state.DirectoryHandle)) { return; } // Get the overlapped pointer to use for this iteration. overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped); int size; continueExecuting = Interop.Kernel32.ReadDirectoryChangesW( state.DirectoryHandle, state.Buffer, // the buffer is kept pinned for the duration of the sync and async operation by the PreAllocatedOverlapped _internalBufferSize, _includeSubdirectories, (int)_notifyFilters, out size, overlappedPointer, IntPtr.Zero); } catch (ObjectDisposedException) { // Ignore. Disposing of the handle is the mechanism by which the FSW communicates // to the asynchronous operation to stop processing. } catch (ArgumentNullException) { //Ignore. The disposed handle could also manifest as an ArgumentNullException. Debug.Assert(IsHandleInvalid(state.DirectoryHandle), "ArgumentNullException from something other than SafeHandle?"); } finally { // At this point the operation has either been initiated and we'll let the callback // handle things from here, or the operation has been stopped or failed, in which case // we need to cleanup because we're no longer executing. if (!continueExecuting) { // Clean up the overlapped pointer created for this iteration if (overlappedPointer != null) { state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); } // Clean up the thread pool binding created for the entire operation state.PreAllocatedOverlapped.Dispose(); state.ThreadPoolBinding.Dispose(); // Finally, if the handle was for some reason changed or closed during this call, // then don't throw an exception. Otherwise, it's a valid error. if (!IsHandleInvalid(state.DirectoryHandle)) { OnError(new ErrorEventArgs(new Win32Exception())); } } } }
//public static string SERVER = "127.0.0.1"; void Start() { inst = this; Security.PrefetchSocketPolicy(SERVER,SocketPolicyServer.PORT,2000); PlayerInfo._id = Math.Abs(((int)DateTime.Now.Ticks))%10000000 * -1; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(SERVER); System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, Shoot3KillServer.PORT); socket.BeginConnect(remoteEndPoint,(IAsyncResult res)=>{ _socket = (Socket) res.AsyncState; _socket.EndConnect(res); bool send_ok = true; _request_thread = new Thread(new ThreadStart(() => { AsyncReadState state = new AsyncReadState(); while (true) { int read = _socket.Receive(state._buffer); if (read > 0) { int start = 0; int i = 0; for (; i < read; i++) { if (state._buffer[i] == (byte)Shoot3KillServer.MSG_TERMINATOR) { state._msg.Append(Encoding.ASCII.GetString(state._buffer,start,i)); msg_recieved(state._msg.ToString()); state._msg.Remove(0,state._msg.Length); start = i + 1; send_ok = true; } } state._msg.Append(Encoding.ASCII.GetString(state._buffer,start,read-start)); } else { Debug.Log ("ERROR::request thread end, server down"); break; } } })); _request_thread.Start(); _send_thread = new Thread(new ThreadStart(() => { while (true) { if ((_socket == null || !_socket.Connected) || !send_ok) { Thread.Sleep(40); continue; } string msg_text = null; bool cont = false; lock (_msg_send_queue) { cont = _msg_send_queue.Count > 0; if (cont) msg_text = _msg_send_queue.Dequeue(); } if (!cont) { Thread.Sleep(40); continue; } byte[] msg_bytes = Encoding.ASCII.GetBytes(msg_text+Shoot3KillServer.MSG_TERMINATOR); _socket.Send(msg_bytes); send_ok = false; } })); _send_thread.Start(); },socket); }
internal int ExecRedirectStdOut(string program, string args, string outFile) { if (program == null) { throw new ArgumentException("program"); } if (args == null) { throw new ArgumentException("args"); } this.TestContext.WriteLine("running command: {0} {1}", program, args); Stream fs = File.Create(outFile); try { System.Diagnostics.Process p = new System.Diagnostics.Process { StartInfo = { FileName = program, CreateNoWindow = true, Arguments = args, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, } }; p.Start(); var stdout = p.StandardOutput.BaseStream; var rs = new AsyncReadState { s = stdout }; Action <System.IAsyncResult> readAsync1 = null; var readAsync = new Action <System.IAsyncResult>((ar) => { AsyncReadState state = (AsyncReadState)ar.AsyncState; int n = state.s.EndRead(ar); if (n > 0) { fs.Write(state.buf, 0, n); state.s.BeginRead(state.buf, 0, state.buf.Length, new System.AsyncCallback(readAsync1), state); } }); readAsync1 = readAsync; // ?? // kickoff stdout.BeginRead(rs.buf, 0, rs.buf.Length, new System.AsyncCallback(readAsync), rs); p.WaitForExit(); this.TestContext.WriteLine("Process exited, rc={0}", p.ExitCode); return(p.ExitCode); } finally { if (fs != null) { fs.Dispose(); } } }
/// <summary> /// Initiates the next asynchronous read operation if monitoring is still desired. /// If the directory handle has been closed due to an error or due to event monitoring /// being disabled, this cleans up state associated with the operation. /// </summary> private unsafe void Monitor(AsyncReadState state) { // This method should only ever access the directory handle via the state object passed in, and not access it // via _directoryHandle. While this function is executing asynchronously, another thread could set // EnableRaisingEvents to false and then back to true, restarting the FSW and causing a new directory handle // and thread pool binding to be stored. This function could then get into an inconsistent state by doing some // operations against the old handles and some against the new. NativeOverlapped* overlappedPointer = null; bool continueExecuting = false; try { // If shutdown has been requested, exit. The finally block will handle // cleaning up the entire operation, as continueExecuting will remain false. if (!_enabled || IsHandleInvalid(state.DirectoryHandle)) return; // Get the overlapped pointer to use for this iteration. overlappedPointer = state.ThreadPoolBinding.AllocateNativeOverlapped(state.PreAllocatedOverlapped); int size; continueExecuting = Interop.mincore.ReadDirectoryChangesW( state.DirectoryHandle, state.Buffer, // the buffer is kept pinned for the duration of the sync and async operation by the PreAllocatedOverlapped _internalBufferSize, _includeSubdirectories, (int)_notifyFilters, out size, overlappedPointer, IntPtr.Zero); } catch (ObjectDisposedException) { // Ignore. Disposing of the handle is the mechanism by which the FSW communicates // to the asynchronous operation to stop processing. } catch (ArgumentNullException) { //Ignore. The disposed handle could also manifest as an ArgumentNullException. Debug.Assert(IsHandleInvalid(state.DirectoryHandle), "ArgumentNullException from something other than SafeHandle?"); } finally { // At this point the operation has either been initiated and we'll let the callback // handle things from here, or the operation has been stopped or failed, in which case // we need to cleanup because we're no longer executing. if (!continueExecuting) { // Clean up the overlapped pointer created for this iteration if (overlappedPointer != null) { state.ThreadPoolBinding.FreeNativeOverlapped(overlappedPointer); } // Clean up the thread pool binding created for the entire operation state.PreAllocatedOverlapped.Dispose(); state.ThreadPoolBinding.Dispose(); // Finally, if the handle was for some reason changed or closed during this call, // then don't throw an exception. Otherwise, it's a valid error. if (!IsHandleInvalid(state.DirectoryHandle)) { OnError(new ErrorEventArgs(new Win32Exception())); } } } }
/// <summary> /// Parse a report sent by the Wiimote /// </summary> /// <param name="buff">Data buffer to parse</param> /// <returns>Returns a boolean noting whether an event needs to be posted</returns> private bool ParseInputReport(byte[] buff) { //try { InputReport type = (InputReport)buff[0]; DataReportAttribute dataReport = EnumInfo <InputReport> .TryGetAttribute <DataReportAttribute>(type); if (dataReport != null) { // Buttons are ALWAYS parsed if (dataReport.HasButtons) { ParseButtons2(buff, dataReport.ButtonsOffset + 1); } switch (dataReport.Interleave) { case Interleave.None: if (dataReport.HasAccel) { ParseAccel2(buff, dataReport.AccelOffset + 1); } if (dataReport.HasIR) { ParseIR2(buff, dataReport.IROffset + 1, dataReport.IRSize); } if (dataReport.HasExt) { ParseExtension2(buff, dataReport.ExtOffset + 1, dataReport.ExtSize); } break; case Interleave.A: interleavedBufferA = buff; interleavedReportA = dataReport; break; case Interleave.B: byte[] buffA = interleavedBufferA; byte[] buffB = buff; DataReportAttribute reportA = interleavedReportA; DataReportAttribute reportB = dataReport; ParseAccelInterleaved2(buffA, buffB, reportA.AccelOffset + 1, reportB.AccelOffset + 1); ParseIRInterleaved2(buffA, buffB, reportA.IROffset + 1, reportB.IROffset + 1); break; } return(true); } else { switch (type) { case InputReport.Status: Debug.WriteLine("******** STATUS ********"); ExtensionType extensionTypeLast = wiimoteState.ExtensionType; bool extensionLast = wiimoteState.Status.Extension; ParseButtons2(buff, 1); ParseStatus2(buff, 3); bool extensionNew = WiimoteState.Status.Extension; using (AsyncReadState state = BeginAsyncRead()) { byte extensionType = 0; if (extensionNew) { ReadByte(Registers.ExtensionType2); } Debug.WriteLine($"Extension byte={extensionType:X2}"); // extension connected? Debug.WriteLine($"Extension, Old: {extensionLast}, New: {extensionNew}"); if (extensionNew != extensionLast || extensionType == 0x04 || extensionType == 0x5) { if (wiimoteState.Extension) { InitializeExtension(extensionType); SetReportType(wiimoteState.ReportType, wiimoteState.IRState.Sensitivity, wiimoteState.ContinuousReport); } else { wiimoteState.ExtensionType = ExtensionType.None; wiimoteState.Nunchuk = new NunchukState(); wiimoteState.ClassicController = new ClassicControllerState(); RaiseExtensionChanged(extensionTypeLast, false); SetReportType(wiimoteState.ReportType, wiimoteState.IRState.Sensitivity, wiimoteState.ContinuousReport); } } } statusDone.Set(); //Respond(OutputReport.Status, true); break; case InputReport.ReadData: Debug.WriteLine("******** READ DATA ********"); ParseButtons2(buff, 1); ParseReadData(buff); break; case InputReport.AcknowledgeOutputReport: Debug.WriteLine("******** ACKNOWLEDGE ********"); ParseButtons2(buff, 1); OutputReport outputType = (OutputReport)buff[3]; WriteResult result = (WriteResult)buff[4]; if (outputType == OutputReport.WriteMemory) { writeDone.Set(); Debug.WriteLine("Write done"); } //Acknowledge(outputType, result); break; default: Debug.WriteLine($"Unknown input report: {type}"); break; } } //} //catch (TimeoutException) { } return(true); }
internal int ExecRedirectStdOut(string program, string args, string outFile) { if (program == null) throw new ArgumentException("program"); if (args == null) throw new ArgumentException("args"); this.TestContext.WriteLine("running command: {0} {1}", program, args); Stream fs = File.Create(outFile); try { System.Diagnostics.Process p = new System.Diagnostics.Process { StartInfo = { FileName = program, CreateNoWindow = true, Arguments = args, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, } }; p.Start(); var stdout = p.StandardOutput.BaseStream; var rs = new AsyncReadState { s = stdout }; Action<System.IAsyncResult> readAsync1 = null; var readAsync = new Action<System.IAsyncResult>( (ar) => { AsyncReadState state = (AsyncReadState) ar.AsyncState; int n = state.s.EndRead(ar); if (n > 0) { fs.Write(state.buf, 0, n); state.s.BeginRead(state.buf, 0, state.buf.Length, new System.AsyncCallback(readAsync1), state); } }); readAsync1 = readAsync; // ?? // kickoff stdout.BeginRead(rs.buf, 0, rs.buf.Length, new System.AsyncCallback(readAsync), rs); p.WaitForExit(); this.TestContext.WriteLine("Process exited, rc={0}", p.ExitCode); return p.ExitCode; } finally { if (fs != null) fs.Dispose(); } }
/// <summary> /// Callback when data is ready to be processed /// </summary> /// <param name="ar">State information for the callback</param> private void OnReadData(IAsyncResult ar) { try { lock (ioLock) { if (device.Stream == null) { return; } if (readStates.Remove(ar)) { // end the current read device.Stream.EndRead(ar); } } } catch (OperationCanceledException) { return; } // grab the byte buffer and other state settings AsyncReadState state = (AsyncReadState)ar.AsyncState; try { /*lock (ioLock) { * if (device.Stream == null) * return; * * // end the current read * device.Stream.EndRead(ar); * }*/ // parse it bool newInput = ParseInputReport(state.Buffer); // post an event //Debug.WriteLine("State Changed Start"); //Debug.WriteLine("State Changed End"); //} // start reading again if (state.ContinueAsync) { //Debug.WriteLine("Read Lock"); BeginAsyncRead(state); //Debug.WriteLine("Read Continue"); } else { Debug.WriteLine($"Read Stop {ReadThreads}"); } if (newInput) { RaiseStateChanged(); } } catch (OperationCanceledException) { //ThrowException(ex); } catch (TimeoutException) { try { // start reading again if (state.ContinueAsync) { BeginAsyncRead(state); } } catch (OperationCanceledException) { } } catch (Exception ex) { RaiseWiimoteException(ex); try { // start reading again if (state.ContinueAsync) { BeginAsyncRead(state); } } catch (OperationCanceledException) { } } }
/// <summary> /// Initiates a read operation from a bulk IN endpoint. /// To enable reading without blocking the main thread, uses an asynchronous delegate. /// </summary> /// /// <remarks> /// To enable reading more than 64 bytes (with device firmware support), increase bytesToRead. /// </remarks> public static void ReadBulkData() { if (DeviceDetected) { const uint bytesToRead = BulkBufferSize; // CH1+CH2+CHD+frame number // Define a delegate for the ReadViaBulkTransfer method of WinUsbDevice. ReadFromDeviceDelegate myReadFromDeviceDelegate = _usbDevice.ReadViaBulkTransfer; // The BeginInvoke method calls MyWinUsbDevice.ReadViaBulkTransfer to attempt // to read data. The method has the same parameters as ReadViaBulkTransfer, // plus two additional parameters: // GetReceivedBulkData is the callback routine that executes when // ReadViaBulkTransfer returns. // MyReadFromDeviceDelegate is the asynchronous delegate object. var readState = new AsyncReadState {Success = false, BytesRead = 0, Data = new byte[BulkBufferSize]}; myReadFromDeviceDelegate.BeginInvoke( Convert.ToByte(_usbDevice.DeviceInfo.BulkInPipe), bytesToRead, ref readState.Data, ref readState.BytesRead, out readState.Success, GetReceivedBulkData, readState ); } }
public void accept_callback(IAsyncResult res) { IOut.Log ("connection start"); Socket listener = (Socket) res.AsyncState; Socket handler = listener.EndAccept(res); _accept_thread_block.Set(); AsyncReadState state = new AsyncReadState(); state._socket = handler; bool send_ok = true; int connection_id = _connection_id_alloc++; AsyncCallback receive_callback = null; receive_callback = new AsyncCallback((IAsyncResult rec_res) => { AsyncReadState rec_state = (AsyncReadState) rec_res.AsyncState; Socket rec_handler = rec_state._socket; try { int read = rec_handler.EndReceive(rec_res); if (read > 0) { int start = 0; int i = 0; for (; i < read; i++) { if (rec_state._buffer[i] == (byte)Shoot3KillServer.MSG_TERMINATOR) { try { rec_state._msg.Append(Encoding.ASCII.GetString(rec_state._buffer,start,i)); } catch (Exception e) {} string stv = rec_state._msg.ToString(); if (stv.Trim() != "") { send_ok = true; msg_recieved(stv,connection_id); } rec_state._msg.Remove(0,rec_state._msg.Length); start = i + 1; } } try { rec_state._msg.Append(Encoding.ASCII.GetString(rec_state._buffer,start,read-start)); } catch (Exception e) {} rec_handler.BeginReceive(rec_state._buffer,0,AsyncReadState.BUFFER_SIZE,0,receive_callback,rec_state); } else { rec_handler.Close(); IOut.Log ("connection closed"); } } catch (SocketException e) { rec_handler.Close(); } catch (Exception e) { rec_handler.Close(); IOut.Log("exception:"+e.GetType()+" msg:"+e.Message+" stack:"+e.StackTrace); } }); handler.BeginReceive(state._buffer,0,AsyncReadState.BUFFER_SIZE,0,receive_callback,state); Thread send_thread = new Thread(new ThreadStart(()=>{ try { while (true) { if (!handler.Connected) break; Thread.Sleep(40); if (!send_ok) continue; send_ok = false; byte[] msg_bytes = Encoding.ASCII.GetBytes(msg_send()+Shoot3KillServer.MSG_TERMINATOR); state._socket.BeginSend(msg_bytes,0,msg_bytes.Length,0,new AsyncCallback((IAsyncResult send_res) => { Socket send_listener = (Socket) send_res.AsyncState; try { send_listener.EndSend(send_res); } catch (Exception e) { send_listener.Close(); } }),state._socket); } } catch (Exception e) {} })); send_thread.Start(); }