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

**URL:** <https://www.ruby-forum.com/t/is-correct-using-io-readpartial-instead-of-io-read/133715>\
**Category:** Ruby\
**Created:** [April 2, 2008, 10:52pm UTC](https://www.ruby-forum.com/t/is-correct-using-io-readpartial-instead-of-io-read/133715 "2008-04-02T22:52:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ISSSSaki\_Baz\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/51bf81/32.png) [@ISSSSaki\_Baz\_C](https://www.ruby-forum.com/u/ISSSSaki_Baz_C)\
**Post date:** [April 2, 2008, 10:52pm UTC](https://www.ruby-forum.com/t/is-correct-using-io-readpartial-instead-of-io-read/133715/1 "2008-04-02T22:52:52Z")

</div>

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

* * *

INVITE sip:user@ip 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.
