Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 507
Jeremy Avatar asked Mar 28 '12 14:03

Jeremy


1 Answers

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
like image 149
maerics Avatar answered Sep 30 '22 04:09

maerics