将stdin键击发送到不需要换行符的频道 [英] Send stdin keystrokes to channel without newline required

查看:183
本文介绍了将stdin键击发送到不需要换行符的频道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在将每个单独的按键输入stdin之后直接将用户的击键发送到频道。

我试过下面的代码,但是这并没有给出想要的结果,因为 reader.ReadByte()方法块,直到进入换行符。

  func chars()<-chan byte {
ch:= make(chan byte)
reader:= bufio.NewReader(os.Stdin)
去func(){
for {
char,err:= reader.ReadByte()
if err!= nil {
log.Fatal(err)
}
ch < - char
}
}()
return ch
}

非常感谢您提供关于如何让每个用户输入字符立即转到频道,而不需要换行符。

解决方案

默认情况下,Stdin是行缓冲的。这意味着它不会给你任何输入,直到遇到换行符。这不是一个Go特有的事情。



让它以非缓冲的方式运行具有高度的平台特定性。正如Rami建议的那样,ncurses是一种方法。另一种选择是更轻的 go-termbox 软件包。



如果您希望手动完成所有操作(至少在Linux上),您可以查看编写 termios 或直接在Go中执行系统调用。



像Windows这样的平台如何处理这个问题,我不知道。您可以深入了解ncurses或termbox的源代码,看看它们是如何做到的。


I'd like to send the user's keystrokes to a channel directly after each individual keystroke is made to stdin.

I've attempted the code below, but this doesn't give the desired result because the reader.ReadByte() method blocks until newline is entered.

func chars() <-chan byte {
    ch := make(chan byte)
    reader := bufio.NewReader(os.Stdin)
    go func() {
        for {           
            char, err := reader.ReadByte()
            if err != nil {
                log.Fatal(err)
            }
            ch <- char
        }
    }()
    return ch
}

Thank you for any advice on how might I get each user input character to go immediately to the channel without the need for a newline character.

解决方案

Stdin is line-buffered by default. This means it will not yield any input to you, until a newline is encountered. This is not a Go specific thing.

Having it behave in a non-buffered way is highly platform specific. As Rami suggested, ncurses is a way to do it. Another option is the much lighter go-termbox package.

If you want to do it all manually (on Linux at least), you can look at writing C bindings for termios or do syscalls directly in Go.

How platforms like Windows handle this, I do not know. You can dig into the source code for ncurses or termbox to see how they did it.

这篇关于将stdin键击发送到不需要换行符的频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆