命令行聊天应用程序中的Java同步输入和输出
我正在尝试使用MulticastSocket为学校练习制作一个控制台聊天应用程序。然而,我的问题是,我不知道如何在客户端键入/等待输入时显示来自另一个人的聊天线路。现在,如果有聊天线路传入,它会中断输入线路(user1的消息直接在目前为止已写出的输入之后): 所以问题是:是否有办法将“username:message”行始终保留在控制台的底部,并让传入的消息在其上方正常打印出来?用户按enter键发送消息后,它会将消息打印到控制台中 到目前为止,我的代码是:命令行聊天应用程序中的Java同步输入和输出,java,multithreading,input,output,chat,Java,Multithreading,Input,Output,Chat,我正在尝试使用MulticastSocket为学校练习制作一个控制台聊天应用程序。然而,我的问题是,我不知道如何在客户端键入/等待输入时显示来自另一个人的聊天线路。现在,如果有聊天线路传入,它会中断输入线路(user1的消息直接在目前为止已写出的输入之后): 所以问题是:是否有办法将“username:message”行始终保留在控制台的底部,并让传入的消息在其上方正常打印出来?用户按enter键发送消息后,它会将消息打印到控制台中 到目前为止,我的代码是: import java.io.*;
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,并将光标移到行的开头,从远程用户处绘制聊天,然后重新绘制提示和用户输入的内容 问题是,您需要能够看到每个用户输入的字符,默认情况下,所有应用程序都以“行模式”启动。见:
没有很好的可移植解决方案可以做到这一点,但如果您只是在Linux或MacOS上运行,则有一些方法可以让它工作。只要您的应用程序仅限于命令行界面,您就必须处理这些问题。更改为GUI会使您的输入流与输出流分离。@dohaqatar7该死,我担心会是这种情况:(我想我必须开始研究如何制作GUI:D谢谢你的回答!对我下面的回答有什么回应吗?嗨,我有同样的问题,但我知道这是一年前的事了。你能找到什么吗?