Is correct using "io.readpartial" instead of "io.read"?

Hi, I’m doing a SIP server (listening in TCP) so I receive messages as
the
following:


INVITE sip:[email protected] SIP/2.0 CRLF
From: xxxxx CRLF
To: xxxxx CRLF
Content-Lenght: 235 CRLF
CRLF
body body body body body body body body body body body body body body
body
body body body body body body body body body body body body body body
body
body body body body body body
body body body body body body body body body

body body body body body body body body body body body body body body
body
body body

I receive and parse correctly the headers and when I detect an empty
line I
must read the number of bytes indicated in “Content-Length” header (235
the
example). This is like SMTP or HTTP.

I wonder which method is better in order to receive the body: io.read or
io.readlines.

io.read blocks after read the 235 bytes while io.readparti

**** io.read
Reads at most length bytes from the I/O stream (blocks).

**** io.readpartial
Reads at most maxlen bytes from the I/O stream. It blocks only if ios
has no
data immediately available. It doesn‘t block if some data available.

The code I use to read the body is:

begin
request.body = io.readpartial(request.hdr_content_length)
rescue EOFError
return
end

For now it works perfectly in both ways but there is an obvious
difference:

With io.readpartial my code reads all the bytes indicated in
Content-Length
(235) just if they come “together”, but if they come “discontinnuated”
io.readpartial return with the read bytes (in the example it can be less
than
235 bytes). Note that I don’t use a loop for io.readpartial.

With io.read the code blocks until read 235 bytes. If the data comes
“not
together” it waits for the 235 bytes.

For now io.readpartial works perfectly and I like it since there could
be a
SIP error (a client sends a body with less bytes than “Content-Length”
says)
and in this way I can detect it inmediately.
But I just do my test in localhost and so, not in real network which can
be
congested, etc.

Any opinion with this please? Thanks a lot.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs