Forum: Ruby TCPsocket send, puts and write

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Brad T. (Guest)
on 2006-04-13 06:18
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
Gyoung-Yoon N. (Guest)
on 2006-04-13 13:58
(Received via mailing list)
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,
Brad T. (Guest)
on 2006-04-13 16:04
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
Gyoung-Yoon N. (Guest)
on 2006-04-13 18:36
(Received via mailing list)
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.
Bill K. (Guest)
on 2006-04-13 22:28
(Received via mailing list)
> 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
This topic is locked and can not be replied to.