Send and receive TCP data in ruby

16,645
require 'socket'
sock = TCPSocket.new('192.168.1.10', 3000)
sock.write 'GETHELLO'
puts sock.read(5) # Since the response message has 5 bytes.
sock.close
Share:
16,645
Jeremy
Author by

Jeremy

Updated on June 14, 2022

Comments

  • Jeremy
    Jeremy almost 2 years

    I have a TCP server running which accepts the command "GETHELLO" and return "HELLO". I test it by using Telnet in linux shell :

    :~$ telnet 192.168.1.10 3000
    Trying 192.168.1.10...
    Connected to 192.168.1.10.
    Escape character is '^]'.
    GETHELLO
    HELLO
    

    How can I do this in ruby using TCPSocket ? (send "GETHELLO" and read the data "HELLO" returned by the server)

    Thanks!