本文介绍了Ruby - 字符式IO.select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 IO.select 返回单个输入字符而不接收 EOF ?我希望能够从键盘读取用户输入,就像我从任何其他流中读取一样,就像打开TCP套接字连接一样。它允许我创建一个这样的事件循环:

Is there a way to have IO.select return a single input character without receiving an EOF? I would like to be able to read user input from the keyboard the same way I read from any other stream, like an open TCP socket connection. It would allow me to make an event loop like this:

loop {
  rd, _, _ = IO.select([long_lived_tcp_connection, stdin])

  case rd[0]
  when long_lived_tcp_connection
    handle_server_sent_event(rd[0].read)
  when stdin
    handle_keypress(rd[0].read)
  end
}

我'我一直在研究 io / console 但它并没有给我这个功能(虽然 IO#getch 非常漂亮关闭)。

I've been looking into io/console but it doesn't quite give me this capability (although IO#getch comes pretty close).

推荐答案

您可以将stdin设置为原始模式(取自):

You can set stdin to raw mode (taken from this answer):

begin
  state = `stty -g`
  `stty raw -echo -icanon isig`
  loop do
    rd, _, _ = IO.select([$stdin])
    handle_keypress(rd[0].getc)
  end
ensure
  `stty #{state}`
end

从stdin返回单个字符。另一种选择是读取所有可用数据。

IO#getc returns a single character from stdin. Another option is IO#read_nonblock to read all available data.

这篇关于Ruby - 字符式IO.select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:51