2017-01-06 32 views
0

我正在试验GNU netcat的-e标志,它允许您将程序附加到TCP套接字,以便它可以使用STDIN/STDOUT发送和接收消息。我在编写一个简单的Ruby程序时遇到了一些麻烦,它会将其输入回送给客户端。以下是我现在有:在Ruby中接收来自STDIN的输入

#!/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的客户端在服务器之前,根本没有输出。我究竟做错了什么?

回答

2

在写入STDOUT之前,Ruby可能会将输出保存在缓冲区中,并且会在打印不确定数量的数据时写入一次。如果你改变你的代码如下:

#!/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服务器之前的客户端”,立即关闭进程将忽略所有尚未刷新的数据。

+0

_“一旦打印了不确定数量的数据,Ruby就只输出到标准输出。” - 严格地说,这是不正确的。 – mudasobwa

+0

改编为精度/挑剔;) – cobaltsoda

+1

我删除了我的答案,因为你的包含更好的解释。尽管考虑在'STDOUT'上使用'$ stdout',因为前者可能会轻松更改。 – mudasobwa

相关问题