Tobbe
Posts: 2
Joined: Tue Dec 02, 2008 5:29 pm
Location: Sweden

How to know when stream have been read to the end?

Tue Dec 02, 2008 5:37 pm

Hi,

I have been playing around with BlueTools for a while talking to a instrument via BT and a serviceStream.
It works great, but now I got into some trouble when I need to send alot of commands after each other and need to know when the response of the first command have been completely read.

In MSDN there is a help for streams that does the exact same thing: http://msdn.microsoft.com/en-us/library ... S.80).aspx

Code: Select all

// Read rs.BufferRead to verify that it contains data. 
      int read = responseStream.EndRead( asyncResult );
      if (read > 0)
      {

      }else
      {
         // Stream has been read completely. Raise an Event.
      }

But when trying this in my app, read is always more than 0.

Is this something with BlueTools and the ServiceStream that makes this impossible or should it work?

best regards,
/Tobias

Jonas
Posts: 2319
Joined: Mon Jan 09, 2006 2:20 pm
Location: Sweden

RE: How to know when stream have been read to the end?

Tue Dec 02, 2008 7:31 pm

You can never know by that logic if you have reached the end of a message.
BeginRead/EndRead will read as much as it can find in the Stream and the immediately return the result.
If you have written 20 bytes and then 20 more, you might get 16 first and then another 16 and finally 4 on the third call to BeginRead. You could also luck out and get 32 first and then 8. This is true for any Stream reading afaik, but it might be more visible with BlueTools since the stream writing/reading is likely slower compared to say a MemoryStream, FileStream or a TCP stream.

When passing messages like this you have to add a header of some kind where it states how large the message will be. That way you can parse the result and know when to make additional calls to BeginRead.

Regards,
Jonas

Tobbe
Posts: 2
Joined: Tue Dec 02, 2008 5:29 pm
Location: Sweden

RE: How to know when stream have been read to the end?

Tue Dec 02, 2008 7:42 pm

Thank you for a quick reply.

Infact I do know how much data I expect as a response for every message, so I will work with that instead.

Return to “BlueTools”