chand1012
chand1012

Reputation: 23

Trying to get client to show command output on a TCP Server made in Ruby

So I am trying to get a TCP Server made in Ruby to show the output of the command on the client, kind of like an SSH server, with Microsoft TelNet as a client. Server Code:

require 'socket'

print "Enter port to open server on:"
port = gets().chomp
server = TCPServer.open(port)

print "Server Ready!\n"

loop do
  client = server.accept
  client.puts "Hello, Please enter 'echo hello'\n"
  loop do
    while line = client.gets
        puts(`#{line}`)
    end
  end
end

To Clarify: I am trying to get the command to output to the Client, as the server output already works.

Upvotes: 1

Views: 788

Answers (1)

chand1012
chand1012

Reputation: 23

So after searching the net some more I came across a blog that held the answer. Link to blog: http://blog.honeybadger.io/capturing-stdout-stderr-from-shell-commands-via-ruby/

So basically one uses a little know library known as 'Open3' to do what I wanted to do, which is capture and output to client 'stdin' and 'status'. In the code I assumed that these statement were at the top:

require 'socket'
require 'open3'

And of course, the opening of the server and the revised code:

port = 80
server = TCPServer.open(port)

loop do
        client = server.accept
        while line = client.gets.chomp # get user input
            begin
                stdin, stdout, status = Open3.capture3("#{line}") #output to console
                puts stdin # put the output to the server
                puts stdout
                puts status
                client.puts stdin # put output to the client
                client.puts stdout
                client.puts status
            rescue # in case the command is incorrect 
                if line == 'closeServer' then # close if this command is given
                    puts "Client #{userInput} closing server!"
                    puts "Closing...."
                    client.puts "Closing server..."
                    client.close
                    exit
                else 
                    puts "Client #{userInput} put invalid command '#{line}'."
                    client.puts "Incorrect command '#{line}'."
                end
            end
        end
    end

Upvotes: 1

Related Questions