我正在尝试使用MulticastSocket进行学校练习的控制台聊天应用程序。然而我的问题是,我不知道如何在客户端输入/等待输入的同时使聊天行来自另一个人显示。现在,如果存在传入的聊天行,它会中断输入行(user1的消息直接在到目前为止写入的输入之后):
所以问题是:无论如何要保持“用户名:message”行始终位于控制台的底部,并让传入的消息正常打印在它上面?用户按Enter键发送消息后,将其打印到控制台中。
到目前为止我的代码:
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());
}
}
}
(这是非常原始的阶段,因为我只是想让输入和输出顺利运行)
答案 0 :(得分:0)
You can implement this on the command line but it is hard. When a chat comes in, you can print a "\r" which is a CR and takes the cursor to the start of the line, draw the chat from the remote user, and then redraw the prompt and the input the user has entered.
The problem is that you would need to be able to see each user input character and by default, all applications start in "line mode". See: How to read a single char from the console in Java (as the user types it)?
There is no good portable solution for doing this but if you are just running on Linux or MacOS there are ways to get it to work.