在 Ruby 中接收来自 STDIN 的输入
Receiving input from STDIN in Ruby
我正在试验 GNU netcat 的 -e
标志,它允许您将程序附加到 TCP 套接字,以便它可以使用 STDIN/STDOUT 发送和接收消息。我在编写一个简单的 Ruby 程序来将其输入回显给客户端时遇到了一些问题。这是我现在拥有的:
#!/usr/bin/env ruby
while line = gets.chomp do
puts line
end
我可以 运行 使用此命令将此程序作为服务器:nc -l -p 1299 -e ./chat-client.rb
。但是如果我使用 nc localhost 1299
连接到我的服务器,我的通信看起来像这样:
输入:
I just don't know.
What is going wrong here?
^C-ing 服务器后的输出:
/chat-client.rb:3:in `gets': Interrupt
from ./chat-client.rb:3:in `gets'
from ./chat-client.rb:3:in `<main>'
I just don't know.
What is going wrong here?
如果我在服务器之前^C 客户端,则根本不会给出任何输出。我做错了什么?
Ruby 可以在写入 STDOUT
之前将输出保存在缓冲区中,并在打印了不确定数量的数据后写入。如果您将代码更改为:
#!/usr/bin/env ruby
while line = gets.chomp do
puts line
STDOUT.flush
# $stdout.flush works too, though the difference
# is outside the scope of this question
end
您可以在关闭输入流之前看到输出。
至于“^C客户端先于服务器”,立即关闭进程将忽略所有尚未刷新的数据。
我正在试验 GNU netcat 的 -e
标志,它允许您将程序附加到 TCP 套接字,以便它可以使用 STDIN/STDOUT 发送和接收消息。我在编写一个简单的 Ruby 程序来将其输入回显给客户端时遇到了一些问题。这是我现在拥有的:
#!/usr/bin/env ruby
while line = gets.chomp do
puts line
end
我可以 运行 使用此命令将此程序作为服务器:nc -l -p 1299 -e ./chat-client.rb
。但是如果我使用 nc localhost 1299
连接到我的服务器,我的通信看起来像这样:
输入:
I just don't know.
What is going wrong here?
^C-ing 服务器后的输出:
/chat-client.rb:3:in `gets': Interrupt
from ./chat-client.rb:3:in `gets'
from ./chat-client.rb:3:in `<main>'
I just don't know.
What is going wrong here?
如果我在服务器之前^C 客户端,则根本不会给出任何输出。我做错了什么?
Ruby 可以在写入 STDOUT
之前将输出保存在缓冲区中,并在打印了不确定数量的数据后写入。如果您将代码更改为:
#!/usr/bin/env ruby
while line = gets.chomp do
puts line
STDOUT.flush
# $stdout.flush works too, though the difference
# is outside the scope of this question
end
您可以在关闭输入流之前看到输出。
至于“^C客户端先于服务器”,立即关闭进程将忽略所有尚未刷新的数据。