public static void WriteToHost( TelnetLogList LogList, byte[] Buffer, NetworkStream NetStream) { if (NetStream.CanWrite == true) { if (LogList != null) { LogList.AddChunk(Direction.Write, Buffer); } NetStream.Write(Buffer, 0, Buffer.Length); TrafficLogFile.Write(Direction.Write, Buffer); } else { throw new Exception("cannot write to network stream"); } }
public void EntryPoint() { this.ThreadEndedEvent.Reset(); try { byte[] buf = new byte[99999]; this.ConnectionFailedException = null; var gotRead = new ManualResetEvent(false); IAsyncResult br = null; int bytesRead = 0; WaitHandle[] handles = new WaitHandle[3]; // loop receiving from the server until: // - the foreground thread wants to shutdown the connection. It has set // the ShutdownFlag event. // - the connection to the server has failed. while ((ShutdownFlag.State == false) && (ConnectionFailedException == null)) { AsyncCallback callBack = null; callBack = ar => { try { bytesRead = this.Client.GetStream().EndRead(ar); gotRead.Set(); // set the gotRead event. one of the events the // WaitAny is waiting on. } catch (ObjectDisposedException) { bytesRead = 0; } catch (InvalidOperationException) { bytesRead = 0; } }; // dequeue and process any message in the InputQueue. if (this.InputQueue.Count > 0) { ReadAndProcessInputQueue(); continue; } try { // start a socket read. ( do not start a new read on every iteration // of this loop. Something may have arrived on the InputQueue. // Meaning the read of the prior iteration is active and is waiting // to complete. ) if (br == null) { br = this.Client.GetStream().BeginRead( buf, 0, buf.Length, callBack, null); } // wait for socket read to complete ( gotRead event is set. ) Or for // something to arrive in the InputQueue. handles[0] = this.ShutdownFlag.EventObject; handles[1] = gotRead; handles[2] = this.InputQueue.GotMessageEvent; var ix = WaitHandle.WaitAny(handles); if (ix == 1) { br = null; gotRead.Reset(); if (bytesRead > 0) { byte[] recvBytes = LoadReceivedBytes(buf, bytesRead); TrafficLogFile.Write(Direction.Read, recvBytes); // print to printer data stream has started. route direct to // printer thread. if ((this.TypeDevice != null) && (this.TypeDevice.Value == TypeTelnetDevice.Printer)) { var printerMessage = new PrinterDataBytesMessage(recvBytes); PostToProcessQueue(printerMessage); } else { ProcessAndPostBytesReceived(recvBytes); } } } } catch (Exception excp) { this.ConnectionFailedException = excp; this.ConnectionFailedEvent.Set(); } } } finally { // in case anyone waiting for this thread to end. Signal the ended event. ThreadEndedEvent.Set(); } }