Jeremy
Jeremy

Reputation: 133

Send and receive TCP data in ruby

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!

Upvotes: 6

Views: 17945

Answers (1)

maerics
maerics

Reputation: 156374

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

Upvotes: 11

Related Questions