我使用 EventMachine LineText2 协议(protocol),我想在每次按下键盘上的字符时触发 receive_line
方法,而不仅仅是在输入新行时触发。有没有办法改变这种默认行为?
class KeyboardHandler < EM::Connection
include EM::Protocols::LineText2
def initialize(q)
@queue = q
end
def receive_line(data)
@queue.push(data)
end
end
EM.run {
q = EM::Queue.new
callback = Proc.new do |line|
# puts on every keypress not on "\n"
puts line
q.pop(&callback)
end
q.pop(&callback)
EM.open_keyboard(KeyboardHandler, q)
}
最佳答案
如果你想从终端接收无缓冲的输入,你应该关闭标准输入的规范模式。 (我还关闭了 echo 以使屏幕更易于阅读。)在您的代码调用 #open_keyboard
之前或在您的处理程序初始化程序中添加:
require 'termios'
# ...
attributes = Termios.tcgetattr($stdin).dup
attributes.lflag &= ~Termios::ECHO # Optional.
attributes.lflag &= ~Termios::ICANON
Termios::tcsetattr($stdin, Termios::TCSANOW, attributes)
例如:
require 'termios'
require 'eventmachine'
module UnbufferedKeyboardHandler
def receive_data(buffer)
puts ">>> #{buffer}"
end
end
EM.run do
attributes = Termios.tcgetattr($stdin).dup
attributes.lflag &= ~Termios::ECHO
attributes.lflag &= ~Termios::ICANON
Termios::tcsetattr($stdin, Termios::TCSANOW, attributes)
EM.open_keyboard(UnbufferedKeyboardHandler)
end
关于ruby - EventMachine 如何编写对按键使用react的键盘处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14474266/