Is this socket code correct?

Juan Cires Martinez jcm at mat.upm.es
Mon Nov 22 17:45:19 UTC 1999


> Do you get to choose the protocol?  If so, you might look at using
> SimpleClientSocket, which has handy commands for sending/receiving a
> line at a time, and for sending/receiving multi-line messages that end
> with a "." on a line by itself.  It will take care of all the
> waitForData's, etc, for you.
> 
Thanks for the suggestion.  Unfortunately, the protocol is fixed (and
binary).

> Otherwise, just remember that a read might return 0 bytes, so you need
> to program for it anyway.  It's not hard to do, you probably need to do
> it anyway, and it asks less of the networking primitives.

Yes, that's what I ended up doing:

  [socket dataAvailable] whileFalse: 
    [(socket waitForDataUntil: Socket standardDeadline) ifFalse: 
      [self error: 'Timeout reading reply']].
  buffer _ ByteArray new: 10000.
  read _ 0.
  [(read < 4) and: [socket dataAvailable]]               "*"
    whileTrue: [read _ socket receiveDataInto: buffer].  "*"

  read < 4
    ifTrue: [self error: 'Too few data read'].

This seems to work, but I worry that I wont be able to detect a time-out
if it happens during the second loop (the one marked "*") since I can
have socket dataAvailable being true and receiveDataInto: reading 0
bytes.

Thanks, Juan.





More information about the Squeak-dev mailing list