我正在尝试编写一个EventMachine服务器,使用ruby 1.9.3的PTY和io/console模块通过telnet或ssh运行nCurses应用程序:

require 'rubygems'
require 'socket'
require 'pty'
require 'io/console'
require 'eventmachine'

 module CursesServer
   def post_init
     puts "-- someone connected to the server!"
     @reader, @writer, @pid = PTY.spawn('ruby ./ncurses_app_to_run.rb')
     @reader.sync = true #No buffering stdout
  end

   def receive_data(data)
     screen = @reader.read(<number_of_bytes>)
     puts "received: " + data # Log input on server side
     send_data screen
     close_connection if data =~ /quit/i
   end

   def unbind
     puts "-- someone disconnected from the server!"
  end
end

# Note that this will block current thread.
EventMachine.run {
  EventMachine.start_server "127.0.0.1", 8081, CursesServer
}

如果我使用传递给@reader.read的参数的值,我可以将屏幕的一部分显示在客户端,但是我不知道如何确定客户端终端的实际大小,无论是初始还是在客户端调整终端大小之后。
如何将输出与客户端终端的大小同步?有没有可能使用telnet/netcat,或者我必须使用像ssh这样更健壮的协议?
提前谢谢。

最佳答案

也许这能帮到你不过,我正在使用EventMachine和ZeroMQ,但它似乎很容易适应。

def run_command command
    _start = Time.now
    begin
      PTY.spawn( command ) do |r, w, pid|
        r.sync = true
        begin
          r.each do |line|
            $announce_socket.send_msg "LOG:#{line}"
          end
       rescue => ex
        puts "ERROR: #{ex.message}"
       end
     end
    rescue PTY::ChildExited => e
      $announce_socket.send_msg "CMD_PREMATURE_EXIT:#{e.message}"
      puts "command exited prematurely, notified UI"
    end
    $announce_socket.send_msg "CMD_EXIT:#{Time.now - _start}"
    puts "done running commmand (took #{Time.now - _start} seconds)"
  end
end

反应堆部分:
$context = EM::ZeroMQ::Context.new(1)

def cleanup(exit_code = 0)
  EM::stop()
  exit exit_code
end

trap('INT') do
  cleanup
end

EM.run do

  $announce_socket = $context.socket ZMQ::DEALER, EMDEALERHandler.new
  $announce_socket.identity = MY_ID
  $announce_socket.connect "tcp://#{host_ip}:7777"

  # announce presence
  $announce_socket.send_msg "UP"
end

在这之后,你只需要一个路由器插座在某处推送数据。

关于ruby - 将PTY输出与Eventmachine同步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13149972/

10-11 17:35