• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Is there a more efficient way to get the first 4 bytes off a NSInputStream to compare
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Is there a more efficient way to get the first 4 bytes off a NSInputStream to compare


  • Subject: Re: Is there a more efficient way to get the first 4 bytes off a NSInputStream to compare
  • From: William Jon Shipley <email@hidden>
  • Date: Tue, 27 Jan 2009 02:57:08 -0800

[inputStream open];
[inputStream read: buffer maxLength:sizeof(buffer)];
...

Note that although your call to -read:maxLength: will work as you expect most of the time, it's not guaranteed to work and is bad practice.

The docs for NSInputStream say this method will "Return the actual number of bytes placed in the buffer" - eg, you're not promised that you'll get all the bytes, just at least 1 byte.

Consider a case where the inputStream represents a TCP/IP socket, and the far side has sent one byte, then got delayed for a minute (or longer), then sent the final three. It's not documented how many bytes you'll get from your call - you could get just one, immediately, or all four, after a minute.

In general, when reading from a network socket, you need to call your read methods in a loop: you attempt a read, check to see if you have all the data, and if not read some more. (The same goes for write methods.)

This is complicated by NS{In,Out}putStreams not having a timeout (that I can find), and it's not clear to me from the documentation whether and when they block waiting for input to arrive (or room to be made on the output buffer).

There is, however, an example at http://developer.apple.com/samplecode/CocoaEcho/listing3.html which appears to be written correctly. It's unfortunately a lot of code right now.

-Wil
_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


  • Follow-Ups:
    • Re: Is there a more efficient way to get the first 4 bytes off a NSInputStream to compare
      • From: Adam Venturella <email@hidden>
  • Prev by Date: Running CATransition in Different Thread ?
  • Next by Date: Re: Not Resolving Aliases
  • Previous by thread: Running CATransition in Different Thread ?
  • Next by thread: Re: Is there a more efficient way to get the first 4 bytes off a NSInputStream to compare
  • Index(es):
    • Date
    • Thread