Send and receive TCP data in ruby

I have a TCP server running that accepts the "GETHELLO" command and returns "HELLO". I am testing it with 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 "HELLO" data returned by the server)

Thank!

+5
source share
1 answer
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
+9
source

All Articles