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.
02bd6b98b7c04f9ae5868eda3d01fb73?d=identicon&s=25 Brad Tilley (rtilley)
on 2006-04-13 04: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
733436f59b64e31c1dd78fc0d29f3cdb?d=identicon&s=25 Gyoung-Yoon Noh (Guest)
on 2006-04-13 11:58
(Received via mailing list)
On 4/13/06, brad tilley <rtilley@vt.edu> 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,
02bd6b98b7c04f9ae5868eda3d01fb73?d=identicon&s=25 Brad Tilley (rtilley)
on 2006-04-13 14:04
Gyoung-Yoon Noh 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
733436f59b64e31c1dd78fc0d29f3cdb?d=identicon&s=25 Gyoung-Yoon Noh (Guest)
on 2006-04-13 16:36
(Received via mailing list)
On 4/13/06, brad tilley <rtilley@vt.edu> 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.
4feed660d3728526797edeb4f0467384?d=identicon&s=25 Bill Kelly (Guest)
on 2006-04-13 20: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.