我正在尝试使用 MulticastSocket 制作一个控制台聊天应用程序用于学校练习。然而我的问题是,我不知道如何在客户端打字/等待输入时显示来自另一个人的聊天行。现在,如果有聊天行传入,它会中断输入行(user1 的消息直接在到目前为止已写出的输入之后):
所以问题是:是否有办法将“用户名:消息”行始终保留在控制台底部,并让传入的消息在其上方正常打印?当用户按下回车键发送消息后,它会将其打印到控制台。
到目前为止我的代码:
import java.io.*;
import java.net.*;
import java.util.*;
public class MulticastChatLahettaja implements Runnable {
//this bool keeps the while-loops running
public static boolean paalla = true;
Thread t;
public MulticastChatLahettaja(){
t = new Thread(this, "ABC");
t.start();
}
@Override
public void run(){
//Here inside the loop it would try to receive packets from the
//socket and print them
while (paalla){
//test chat lines
System.out.println("user1: some chat lines, mumble mumble...");
try{
//Put the thread to sleep for 5s to prevent spamming
//when testing
Thread.sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//Around here it connects to the MulticastSocket
String ip = "239.0.0.1";
int portti = 6666;
Console console = System.console();
//Enters name
String nimi = console.readLine("Syota Nimi:");
//start Thread
new MulticastChatLahettaja();
System.out.println("Liityttiin ip: "+ip+", porttiin: "+Integer.toString(portti)+", nimella: "+nimi);
System.out.println("Sulje asiakas syottamalla ':quit'");
try {
//In here I'm waiting for the input and sending it to the Socket
while (paalla) {
String syote = console.readLine(nimi+": ");
//If input is ":quit" it stops the loops and application closes
if (syote.equals(":quit")) paalla = false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
(这还处于非常原始的阶段,因为我只是想让输入和输出顺利工作)
最佳答案
你可以在命令行上实现这个,但是很难。当聊天进入时,您可以打印一个“\r”(即 CR)并将光标移至行首,绘制来自远程用户的聊天,然后重新绘制提示和用户输入的内容。
问题是您需要能够看到每个用户输入的字符,并且默认情况下,所有应用程序都以“行模式”启动。请参阅:How to read a single char from the console in Java (as the user types it)?
没有好的可移植解决方案可以做到这一点,但如果您只是在 Linux 或 MacOS 上运行,则有一些方法可以让它工作。
关于命令行聊天应用程序中的Java同步输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921352/