I have to take a dump of a service in sinatra and display it in the content area of the webpage.
The Service I have to access via code runs on server at port 6557. It doesnt use any encryption or authentication. Its a plain readonly request response thingy like http. Here is what works in teminal
$ echo "GET hosts" | nc 192.168.1.1 6557
gives me the intended output. I need to do something similar using the sinatra application.
I wrote this code but is grossly incorrect. Can sombody help me with code or lookup materials or examples.
get '/' do
host = "192.168.1.1"
port = 6557
dat = ""
@socket = TCPSocket.open (host, port)
while(true)
if(IO.select([],[],[@socket],0))
socket.close
return
end
begin
while( (data = @socket.recv_nonblock(100)) != "")
dat = dat+ data
end
rescue Errno::EAGAIN
end
begin
@str = "GET hosts"
@socket.puts(@str);
rescue Errno::EAGAIN
rescue EOFError
exit
end
IO.select([@socket], [@socket], [@socket])
end
@line = dat
erb :info
end
The code on execution just hangs up. Also if possible please give some links to read up to get a conceptual context of the problem.
You can execute shell commands directly from ruby using backticks or the system
command. Something like this may work for you:
get "/" do
@line = `echo "GET hosts" | nc 192.168.1.1 6557`
erb :info
end
Check out the ruby docs for Kernel#system for more info.
I think the Ruby equivalent to your shell command should be as simple as:
require "socket"
socket = TCPSocket.new "192.168.1.1", 6557
socket.puts "GET hosts"
socket.read
According to the docs, #read should close the socket automatically, so you don't need to worry about doing that manually.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.