如何使用 ruby​​ 的 net/telnet 读取整行? [英] how to read whole lines using ruby's net/telnet?

查看:20
本文介绍了如何使用 ruby​​ 的 net/telnet 读取整行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ruby​​ 中使用 net/telnet 库从服务器读取数据.它将命令作为整行发送,最后有一个换行符,所以我想我会这样做:

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

我经常会得到这个:

COMMAND1 option1 option2 option3
COMMAND2 option1 option2 option3
COMMAND3 opt

然后我将在下一次阅读中了解 COMMAND3 的其余选项,以及 COMMAND4.

and then I'll get the rest of COMMAND3's options in the next read, along with COMMAND4.

有什么办法可以让 net/telnet 向我发送以换行符分隔的文本?或者另一种方法来解决这个问题?

Is there any way I can get net/telnet to just send me text delimited on the newlines? Or another way to fix this?

谢谢,斯图尔特

推荐答案

这是我目前的解决方案,我不确定这是否是最好的方法,但它在我的实时数据源上运行正常:

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

这篇关于如何使用 ruby​​ 的 net/telnet 读取整行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆