拦截键盘按键压入Docker容器

问题描述 投票:0回答:1

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

我正在使用以下命令来运行以蛇游戏为图像名称的容器。

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

有什么办法解决此问题?

c# docker .net-core containers console-application
1个回答
0
投票

除了-t-i还需要传递docker run标志:

docker run

这是“将终端附加到程序”的另一种说法。文档对此非常明确:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.