Reputation: 14449
I'm using the net/telnet library in ruby to read data from a server. It's sending commands as whole lines with a newline at the end, so I thought I'd do this:
connection = Net::Telnet.new(options)
connection.waitfor(/\n/) do |txt|
process txt
end
That doesn't work because it sends me a whole bunch of lines all at once. I can fix that fairly easily by instead doing:
connection.waitfor(/\n/) do |txt|
txt.split("\n").each do |line|
process line
end
end
Except there's a problem with that too: the string I'm sent almost always contains half a command at the end. i.e.: if the server was sending this:
COMMAND1 option1 option2 option3
COMMAND2 option1 option2 option3
COMMAND3 option1 option2 option3
I'll often get this:
COMMAND1 option1 option2 option3
COMMAND2 option1 option2 option3
COMMAND3 opt
and then I'll get the rest of COMMAND3's options in the next read, along with COMMAND4.
Is there any way I can get net/telnet to just send me text delimited on the newlines? Or another way to fix this?
Thanks, Stewart
Upvotes: 2
Views: 1577
Reputation: 14449
So this is my current solution, I'm not sure if it's the best way to go but it works okay on my live data source:
connection = Net::Telnet.new(options)
all_text = ""
while running do
connection.waitfor(/\n/) do |server_text|
all_text += server_text
while cmd = all_text.slice!(/^.*\n/) do
process cmd
end
# any half-command remains in all_text at this point
end
end
Upvotes: 1