首页 > 解决方案 > 将扫描仪输入保留在控制台底部

问题描述

我目前正在为一个打算介绍套接字编程和多线程编程的学校项目编写一个小型 CLI。我们基本上是在实现一种文件传输协议。我目前在格式化 CLI 时遇到了一些问题。由于程序的多线程特性,有时会请求输入,然后显示输出。这使得用户和 CLI 之间的整体交互变得尴尬,因为现在用户必须在输出发生后输入输入。

我想知道是否有一种方法,使用标准 Java I/O,即使有新消息进来,也可以将输入始终保持在 CLI 的底部。

例如,当前的输出如下所示:

Connected to 127.0.0.1:5000 and 127.0.0.1:5001
mytftp> pwd
/Users/Shawn/Desktop/Computer Science/CSCI4780 Distributed Systems/Project2/server
mytftp> pwd &
mytftp> 
/Users/Shawn/Desktop/Computer Science/CSCI4780 Distributed Systems/Project2/server
ls
.DS_Store
sdf
clientFile.txt
mytftp> 

但我期待这样的事情:

Connected to 127.0.0.1:5000 and 127.0.0.1:5001
mytftp> pwd
/Users/Shawn/Desktop/Computer Science/CSCI4780 Distributed Systems/Project2/server
mytftp> pwd &
/Users/Shawn/Desktop/Computer Science/CSCI4780 Distributed Systems/Project2/server
mytftp> ls
.DS_Store
sdf
clientFile.txt
mytftp> 

注意:这里的“&”表示“在单独的线程上运行此命令”。这就是为什么在下一次执行期间,首先出现“mytftp>”提示,然后显示线程的结果。我希望当前提示始终保持在底部。旁注,pwd 命令上的 & 未添加以提高性能。它通常仅用于文件上传和下载命令,但在这里用作示例。

我不确定这是否可能,但我们将不胜感激。

重申一下,流程希望

Connection Established:连接到 127.0.0.1:5000 和 127.0.0.1:5001
Command is entered into new thread: mytftp> pwd &
Next prompt is shown ready for a new command: mytftp>

一旦结果pwd &进来,我希望提示下来:

Connection Established:连接到 127.0.0.1:5000 和 127.0.0.1:5001:mytftp
Command is entered into new thread> pwd &
Space was made for the prompt and results shown:/Users/Shawn/Desktop/Computer Science/CSCI4780 分布式系统/Project2/server
Next prompt is shown ready for a new command:mytftp>

标签: javaiojava.util.scanner

解决方案


我最终想出的解决方案是使用\r角色并重新安排提示流。而不是:

while true:
    show prompt
    get input
    do some socket programming here

我选择使用以下架构

show prompt
while true:
    get input
    do some socket programming here and each socket response (system.out) should start with \r, followed by the message, followed by "\nmytftp>".

这意味着来自服务器的每条消息都将删除当前提示,但使用回车,然后将提示添加回它之前。


推荐阅读