/// <summary> /// Обработчик данных. Чтение/Запись данных осуществляется синхронно. /// </summary> protected override EventWaitHandle DoLoopInner(NetworkStream ns, TransferState ts) { byte[] bufferread = new byte[4096]; byte[] bufferwrite = null; int count; ts.Reset(); while ((count = ns.Read(bufferread, 0, bufferread.Length)) > 0) { ts.AddReadBytes(count); #if VERBOSE //if (totalreadbytes % 10000 == 0) ConsoleLogger.LogMessage("read: " + totalreadbytes); #endif bool EOFPresent = HandleBuffer(bufferread, count,answer, out bufferwrite); ns.Write(bufferwrite, 0, bufferwrite.Length); ts.AddWriteBytes(bufferwrite.Length); if (EOFPresent) break; } return new ManualResetEvent(true); }
protected override EventWaitHandle DoLoopInner(NetworkStream ns, TransferState ts) { byte[] bufferread = new byte[1024*1]; byte[] bufferwrite =null; int count; ManualResetEvent mreDone = new ManualResetEvent(false); AsyncCallback readcallback=null; readcallback = ar_c => { try { count = ns.EndRead(ar_c); ts.AddReadBytes(count); #if VERBOSE //if (ts.totalreadbytes % 10000 == 0) ConsoleLogger.LogMessage("read: " + ts.totalreadbytes); #endif bool EOFPresent = false; if (count > 0) { EOFPresent = HandleBuffer(bufferread, count, answer, out bufferwrite); ns.Write(bufferwrite, 0, bufferwrite.Length); if (bufferwrite != null) { ts.AddWriteBytes(bufferwrite.Length); } } if (EOFPresent == false && count>0) { ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts); } else { mreDone.Set(); } } catch (IOException ioe) { if (ioe.InnerException != null) { SocketException se = ioe.InnerException as SocketException; if (se != null) { if (se.SocketErrorCode == SocketError.ConnectionReset) { ConsoleLogger.LogMessage("Client closed connection!"); mreDone.Set(); return; } } ObjectDisposedException ode = ioe.InnerException as ObjectDisposedException; if (ode != null) { ConsoleLogger.LogMessage("Client closed connection."); mreDone.Set(); return; } } throw ioe; } catch (Exception ex) { ConsoleLogger.LogMessage("Error in readcallback: " + ex.ToString()); mreDone.Set(); } }; //начинаем асинхронное чтение данных ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts); //ожидаем завершения обработки mreDone.WaitOne(); //обработка завершена ConsoleLogger.LogMessage("Thread shutdown!"); return mreDone; }