How to correctly handle partial write in Ruby Sockets?

TCP sockets are streams, not messages, so berkeley sockets send()
function on some systems may send less data than required. Since Ruby
Socket is very thin wrapper over berkeley sockets, AFAIK Socket#send
will behave exactly like berkeley sockets send(). So what is the
correct way to send a complete message via Ruby TCP sockets? In python
it’s a special function for that called sendall(). But in Ruby i need
to manually write code like that:

while (sent = sock.send( data, 0 ) < data.length do
data = data[ sent…-1 ]
end

On Wed, Oct 26, 2011 at 9:01 AM, Grigory P. [email protected]
wrote:

end
In blocking mode you can simply do

sock.write(data)

Kind regards

robert

Thanks for reply.

I have checked source code for IO.write previously (Socket is
inherited from BasicSocket that is inherited from IO, as i can see).
It’s a wrapper over POSIX write() function. And according to POSIX
documentation, write() for sockets is exactly same as send() - just
without flags.

Why do you think write() will help? Maybe i miss something?

Best,
Grigory.

On Wed, Oct 26, 2011 at 11:12 AM, Robert K.

Grigory P. wrote in post #1028553:

I have checked source code for IO.write previously (Socket is
inherited from BasicSocket that is inherited from IO, as i can see).
It’s a wrapper over POSIX write() function. And according to POSIX
documentation, write() for sockets is exactly same as send() - just
without flags.

Why do you think write() will help? Maybe i miss something?

Because ruby’s write will keep calling the underlying system write()
until the complete message is sent. You don’t have to worry about it.

On Wed, Oct 26, 2011 at 11:04 AM, Grigory P. [email protected]
wrote:

Thanks for reply.

You’re welcome.

I have checked source code for IO.write previously (Socket is
inherited from BasicSocket that is inherited from IO, as i can see).
It’s a wrapper over POSIX write() function. And according to POSIX
documentation, write() for sockets is exactly same as send() - just
without flags.

Why do you think write() will help? Maybe i miss something?

I used it - and it works. Try it out yourself if you do not believe it.

Btw, #send will also block until the message is completely sent unless
you are in nonblocking mode.

Cheers

robert

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