TCPsocket send, puts and write


#1

What are the differences (if any) between these methods of sending data:

t = TCPsocket.new(host, port)
t.write(a_string)
t.close

t = TCPsocket.new(host, port)
t.puts(a_string)
t.close

t = TCPsocket.new(host, port)
t.send(a_string)
t.close


#2

On 4/13/06, brad tilley removed_email_address@domain.invalid wrote:

t = TCPsocket.new(host, port)
t.send(a_string)
t.close


Posted via http://www.ruby-forum.com/.

Hi,

$ irb
irb(main):001:0> require ‘socket’
=> true
irb(main):002:0> ts = TCPSocket.new(‘0’, 80)
=> #TCPSocket:0xb7cb2ddc
irb(main):003:0> m1 = ts.method(:send)
=> #<Method: TCPSocket(BasicSocket)#send>
irb(main):004:0> m2 = ts.method(:write)
=> #<Method: TCPSocket(IO)#write>
irb(main):005:0> m3 = ts.method(:puts)
=> #<Method: TCPSocket(IO)#puts>

TCPSocket#send and TCPSocket#write are functionally same.
But TCPSocket#puts appends “\n” to the output string.

HTH,


#3

Gyoung-Yoon N. wrote:

TCPSocket#send and TCPSocket#write are functionally same.
But TCPSocket#puts appends “\n” to the output string.

HTH,

Yes, thank you for the example. I have been using write, but I did not
see many examples using this method while lots of examples use send and
puts. Should I use send rather than write? Will write be deprecated
someday?

Thanks


#4

TCPSocket#send and TCPSocket#write are functionally same.

I think #write will block until all the data is sent, whereas #send
may return immediately, having sent only part of the data.

With #send you may need a loop like this:

def send_string(sock, str)
begin
while str.length > 0
sent = sock.send(str, 0)
str = str[sent…-1]
end
rescue IOError, SocketError, SystemCallError
# eof = true
end
end

Regards,

Bill


#5

On 4/13/06, brad tilley removed_email_address@domain.invalid wrote:

Thanks


Posted via http://www.ruby-forum.com/.

Ruby’s standard socket library is very similar to BSD socket interface:
send(2) and write(2).

I guess ruby’s socket library will support both send and write methods
consistently along with POSIX as such other cases.