Receiving input from STDIN in Ruby

2.6k views Asked by At

I'm experimenting with GNU netcat's -e flag, which allows you to attach a program to a TCP socket so that it can send and receive messages with STDIN/STDOUT. I'm having some trouble writing a simple Ruby program that echoes it's input back to the client. Here is what I have now:

#!/usr/bin/env ruby

while line = gets.chomp do
    puts line
end

I can run this program as a server with this command: nc -l -p 1299 -e ./chat-client.rb. But if I connect to my server using nc localhost 1299, my communication looks like this:

Input:

I just don't know.
What is going wrong here?

Output after ^C-ing the server:

/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?

If I ^C the client before the server, no output is given at all. What am I doing wrong?

1

There are 1 answers

5
AudioBubble On BEST ANSWER

Ruby may hold output in a buffer before writing to STDOUT, and write once an indeterminate amount of data has been printed. If you change your code to this:

#!/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

You can expect to see the output before you close the input stream.

As for "^C the client before the server", closing the process immediately will disregard all of the data which has not yet been flushed.