拦截键盘按键进入 docker 容器

Intercept Keyboard Key presses into a docker container

我正在尝试将控制台应用程序游戏包装到 docker 容器中,并且有必要捕捉键盘上按下的箭头键。

密码是:

public static Direction ReadInputDirection()
{
    var key = Console.ReadKey(intercept: true);

    switch (key.Key)
    {
        case ConsoleKey.UpArrow:
            return Direction.Up;

        case ConsoleKey.DownArrow:
            return Direction.Down;

        case ConsoleKey.LeftArrow:
            return Direction.Left;

        case ConsoleKey.RightArrow:
            return Direction.Right;

        default:
            return Direction.Invalid;
    }
}

上面的代码抛出以下异常:

Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read. at System.ConsolePal.ReadKey(Boolean intercept) at SnakeGame.Control.ReadInputDirection()

我正在使用以下命令 运行 snake-game 是图像名称的容器。

docker run -i --name snake-game snake-game

有什么办法可以解决这个问题吗?

除了 -i 之外,您还需要将 -t 标志传递给 docker run

-t              : Allocate a pseudo-tty

这是另一种说法 "attach a terminal to the program"。文档对此相当明确:

For interactive processes (like a shell), you must use -i -t together in order to allocate a tty for the container process. -i -t is often written -it as you’ll see in later examples.

没有终端(又名 tty),程序无法读取输入和错误,就像您看到的那样。