【问题标题】:Intercept Keyboard Key presses into a docker container拦截键盘按键进入 docker 容器
【发布时间】:2019-10-03 14:11:10
【问题描述】:

我正在尝试将控制台应用程序游戏包装到 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;
    }
}

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

未处理的异常:System.InvalidOperationException:无法读取 当任一应用程序没有控制台或控制台时的键 输入已被重定向。试试 Console.Read。在 System.ConsolePal.ReadKey(布尔截距)在 SnakeGame.Control.ReadInputDirection()

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

docker run -i --name 蛇游戏蛇游戏

有没有办法解决这个问题?

【问题讨论】:

  • 嗨 Rodrigo,您的代码在您的机器上运行正常吗?您可以编辑您的问题并放置您的 Dockerfile 吗?

标签: c# docker .net-core containers console-application


【解决方案1】:

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

-t              : Allocate a pseudo-tty

这是“将终端连接到程序”的另一种说法。文档对此相当明确:

对于交互式进程(如 shell),您必须一起使用 -i -t 才能为容器进程分配一个 tty。 -i -t 通常写成 -it,您将在后面的示例中看到。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2011-10-25
    相关资源
    最近更新 更多