I'm trying to make an console chat application using MulticastSocket for school exercise. However my problem is that I don't know how I can make the chat lines coming from another person display whilst the client is typing/waiting for input. Now if there is chat lines incoming, it interrupts the inputline as so (user1's message goes directly after the input that has been written out so far):
So the question is: is there anyway to keep the "username: message" line always in the bottom of the console and let the incoming messages print out normally above it? And after the user presses enter to send message, it prints it into the console.
My code so far:
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());
}
}
}
(It is very raw stage yet, since I'm just trying to get the input and output to work smoothly)