如何使用 ruby 的 net/telnet 读取整行?
我正在使用 ruby 中的 net/telnet 库从服务器读取数据。它以整行的形式发送命令,最后有一个换行符,所以我想我会这样做:
connection = Net::Telnet.new(options)
connection.waitfor(/\n/) do |txt|
process txt
end
这不起作用,因为它一次向我发送了一大堆行。我可以通过这样做来相当容易地解决这个问题:
connection.waitfor(/\n/) do |txt|
txt.split("\n").each do |line|
process line
end
end
除了这也有一个问题:我发送的字符串几乎总是在末尾包含半个命令。即:如果服务器发送此:
COMMAND1 option1 option2 option3
COMMAND2 option1 option2 option3
COMMAND3 option1 option2 option3
我经常会收到此:
COMMAND1 option1 option2 option3
COMMAND2 option1 option2 option3
COMMAND3 opt
然后我将在下一次读取中获得 COMMAND3 的其余选项以及 COMMAND4。
有什么方法可以让 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我当前的解决方案,我不确定这是否是最好的方法,但它在我的实时数据源上运行良好:
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: