private void StartReadThread() { if (this._tcpClient != null && this._tcpClient.Connected) // Read 4-bit Length Header { this.__dataBuffer = new byte[4]; System.Net.Sockets.NetworkStream clientStream = this._tcpClient.GetStream(); if (clientStream.CanRead) { IAsyncResult iar = clientStream.BeginRead(__dataBuffer, 0, 4, new AsyncCallback(this.EndReadFromClient), clientStream); iar.AsyncWaitHandle.WaitOne(); } } }
private void OnRecive() { while (true) { Thread.Sleep(10); if (m_Tcp == null || m_Tcp.Connected == false) { OnError(MessageRetCode.MRC_DISCONNECT); return; } System.Net.Sockets.NetworkStream stream = m_Tcp.GetStream(); if (stream.CanRead) { stream.BeginRead(m_RecvBuffer, 0, m_RecvBuffer.Length, new AsyncCallback(OnAsyncRead), stream); m_AllDone.WaitOne(); } } }
public void ReceiveDataAndEnqueue() { log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; log.WriteLog("ReceiveData and Enqueue thread started..."); string s; int iCRat, iCRcount; string [] sa; int length = 0; string sLastErrorMessage = ""; while (!m_bDone) { try { try { m_NetworkStream = m_TCPClient.GetStream(); System.IAsyncResult asr = m_NetworkStream.BeginRead(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength - m_iBufferLength,null,null); while (!asr.IsCompleted && !m_bDone) { System.Threading.Thread.Sleep(100); } if (m_bDone) { continue; } //asr.AsyncWaitHandle.WaitOne(); length = m_NetworkStream.EndRead(asr); } catch (System.IO.IOException ioex) { if (null != ioex.InnerException) { if (ioex.InnerException is System.Net.Sockets.SocketException) { int iErrorCode = ((System.Net.Sockets.SocketException)ioex.InnerException).ErrorCode; string sErrorMessage = ((System.Net.Sockets.SocketException)ioex.InnerException).Message; sLastErrorMessage = "ReceiveDataAndEnqueue: Error Code = " + iErrorCode.ToString() + " Description = " + sErrorMessage; } else { sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ioex.Message; } log.WriteLog(sLastErrorMessage); } m_bDone = true; m_bConnected = false; } catch (System.Exception ex) { sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ex.Message; log.WriteLog(sLastErrorMessage); m_bDone = true; m_bConnected = false; } if(!m_bConnected) { OnConnectionErrorReceived(this,sLastErrorMessage); continue; } if (m_bDone) continue; if (0 == length) { // connection must have been reset m_bDone = true; m_bConnected = false; continue; } m_iBufferLength += length; // find all the messages in the stream iCRcount = 0; for (int i = 0; i < m_iBufferLength; i++) { if (m_bytesIncomingBuffer[i] == 13) iCRcount++; } // for // post all messages from the stream for (int i = 0; i < iCRcount; i++) { s = System.Text.Encoding.ASCII.GetString(m_bytesIncomingBuffer); s = s.Substring(0,m_iBufferLength); iCRat = s.IndexOf((char)13); if (-1 != iCRat) { int iLen; s = s.Substring(0,iCRat); iLen = s.Length + 1; m_iBufferLength -= iLen; m_sLastResponse = s; lock (m_qCommands.SyncRoot) { CarverLab.Oyster.Encoder.Command cmd; string [] saParams; sa = CarverLab.Oyster.Encoder.Command.DecodeCommand(System.Text.Encoding.ASCII.GetBytes(s),s.Length); if (sa.Length > 1) { saParams = new string[sa.Length - 1]; Array.Copy(sa,1,saParams,0,sa.Length - 1); cmd = new CarverLab.Oyster.Encoder.Command(sa[0],saParams); } else { cmd = new CarverLab.Oyster.Encoder.Command(sa[0],null); } m_qCommands.Enqueue(cmd); } byte [] bytes = new byte[m_iBufferLength]; Array.Copy(m_bytesIncomingBuffer,0,bytes,0,m_iBufferLength); CarverLab.Oyster.Encoder.CommandEventArgs cea = new CarverLab.Oyster.Encoder.CommandEventArgs(bytes, ref m_qCommands); OnMessageReceived(cea); m_EventMessageAvailable.Set(); Array.Copy(m_bytesIncomingBuffer,iLen,m_bytesIncomingBuffer,0,m_iBufferLength); Array.Clear(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength - m_iBufferLength); } // if } // for } catch (System.Exception ex) { log.WriteLog("Exception: " + ex.Message); } } // while m_EventThreadComplete.Set(); }
protected bool readBytes(System.Net.Sockets.NetworkStream ns, System.IO.MemoryStream response, System.String waitFor, bool machresponseend) { bool error = false; byte[] readBytes = new byte[client.ReceiveBufferSize]; int nbytes = 0; System.String lastBoundary = System.String.Empty; if (log.IsDebugEnabled) { log.Debug("Reading response"); } System.IAsyncResult result = ns.BeginRead(readBytes, 0, readBytes.Length, null, null); for (long waiting = 0; !error && ns.CanRead && result != null; nbytes = 0) { try { if (!result.IsCompleted) { System.Threading.Thread.Sleep(50); waiting += 50; } if (result.IsCompleted) { nbytes = ns.EndRead(result); result = null; waiting = 0; } else if (waiting > this.timeoutResponse) { lastErrorMessage = "Read timeout"; if (log.IsErrorEnabled) { log.Error(lastErrorMessage); } result = null; error = true; } } catch (System.Exception e) { error = true; nbytes = 0; lastErrorMessage = "Read error"; if (log.IsErrorEnabled) { log.Error(lastErrorMessage, e); } } if (!error && nbytes > 0) { if (log.IsDebugEnabled) { log.Debug("Read " + nbytes + " bytes"); } response.Write(readBytes, 0, nbytes); // Only test waitfor secuence if there is no data for reading // and there are enouth data available for comparing if (!ns.DataAvailable && response.Length > waitFor.Length) { // The waitfor text must be the last portion of the response if (machresponseend) { response.Seek(response.Length - waitFor.Length, System.IO.SeekOrigin.Begin); response.Read(readBytes, 0, waitFor.Length); lastBoundary = System.Text.Encoding.ASCII.GetString(readBytes, 0, waitFor.Length); // The waitfor text must be in the begining of the last line of the response } else { response.Seek(0, System.IO.SeekOrigin.Begin); System.IO.StreamReader reader = new System.IO.StreamReader(response); System.String line = System.String.Empty; for (System.String tmp = reader.ReadLine(); tmp != null; line = tmp, tmp = reader.ReadLine()) { } if (line != null && line.Length >= waitFor.Length) { lastBoundary = line.Substring(0, waitFor.Length); } reader.DiscardBufferedData(); reader = null; response.Seek(0, System.IO.SeekOrigin.End); } } // We haven't finished, so start a new async read if (lastBoundary != waitFor) { result = ns.BeginRead(readBytes, 0, readBytes.Length, null, null); } } } response.Flush(); if (log.IsDebugEnabled) { log.Debug(System.String.Concat("Reading response finished. Error: ", error, ", lenght: ", response.Length)); } // Discard response if there has been a read error. if (error) { response.SetLength(0); } else if (response.Length == 0) { error = true; } return(!error); }