Hey guys, im using this code to send and receive via rs232 com port


problem is, i want to receive right after i send. I need to know how many bytes to receive, so before receiving, i run a function that figures that out. What i think is happening is that its running too fast and isnt waiting for the entire message to come back. Therefore the buffer is smaller than what is should be. Heres so code:

send function
VB Code:
  1. Public Sub sendData(ByVal sTx As String)
  2.  
  3.         '----------------------
  4.  
  5.  
  6.  
  7.         '// Clear Tx/Rx Buffers
  8.         moRS232.PurgeBuffer(Rs232.PurgeBuffers.TxClear Or Rs232.PurgeBuffers.RXClear)
  9.  
  10.         'sTx = sendBox.Text
  11.         sendBox.Text = sTx
  12.  
  13.         If chkAddCR.Checked Then sTx += ControlChars.Cr
  14.         moRS232.Write(sTx)
  15.  
  16.         debugThis("Message Sent: " + sTx)
  17.  
  18.         '//clear text box
  19.         'sendBox.Text = String.Empty
  20.         'sendBox.Refresh()
  21.         lbHex.Items.Clear()
  22.         If chkAutorx.Checked Then Button1_Click(Nothing, Nothing)
  23.  
  24.        receivedata()
  25.  
  26.     End Sub

receive function:
VB Code:
  1. Private Sub receiveData()
  2.  
  3.  
  4.         Try
  5.             'first see how many bits are waiting to be read in
  6.             bytesRemain = moRS232.InBufferCount.ToString()
  7.             bytesRemaining.Text = bytesRemain
  8.  
  9.             ''MsgBox("going to read in " + CStr(bytesRemain) + " bytes")
  10.  
  11.             moRS232.Read(Int32.Parse(bytesRemain))
  12.             receiveBox.Text = moRS232.InputStreamString
  13.             receiveBox.ForeColor = Color.Black
  14.             receiveBox.BackColor = Color.White
  15.             '// Fills listbox with hex values
  16.             Dim aBytes As Byte() = moRS232.InputStream
  17.  
  18.             Dim iPnt As Int32
  19.             For iPnt = 0 To aBytes.Length - 1
  20.                 lbHex.Items.Add(iPnt.ToString & ControlChars.Tab & String.Format("0x{0}", aBytes(iPnt).ToString("X")))
  21.             Next
  22.  
  23.             debugThis("Message Received: " + moRS232.InputStreamString)
  24.         Catch Ex As Exception
  25.             receiveBox.BackColor = Color.Red
  26.             receiveBox.ForeColor = Color.White
  27.             receiveBox.Text = moRS232.InputStreamString
  28.             debugThis("Error: Could not read data")
  29.  
  30.             errorBox.Text = "Error: " & Ex.Message & "  data fetched: " & moRS232.InputStreamString
  31.         End Try
  32.     End Sub