I'm making a console chat application and now I have some problems with displaying messages on the client program.
My client program has two threads a read thread and write thread. The read thread gets messages from the server and write sends messages. The write thread has a Console object reading one line with a some text indicating to the user where to write your message. It looks like this in the console:
[Username]: message goes here
And this works fine when you only want to send messages, but I also have a read thread which is receiving and displaying messages that it got from the server. Which messes up this whole input thing because for example when the read thread gets a message it just prints it to the console and then prints another indicator on the next line and then everything looks like this:
[Username]:
[qwerty]: hello
[Username]:
I tried deleting the first indicator by printing \b (backspace) escape character in a for loop that looks like this:
String username = "username";
String indicator = "[" + username + "]: ";
for (int i = 0; i < indicator.length(); i++)
{
System.out.print("\b");
}
It worked on regular text, but not on the indicator. I think that's because the Console object reading for input in the same line somehow gets in the way.
This problem is even worse when the user is typing out a message and in the middle of the typing the user gets a message this happens:
[Username]: Hel //the user wanted to type out hello but got cut off
[qwerty]: hello
[Username]:
If the user where to finish writing hello on the next line and then send it. For the other client the message would say hello with no sign that the clients writing was interrupted by him, but for the client writing the message it would look like it sent two separate messages. I don't know how to fix this at all. Any help is appreciated.
Code for write thread:
public static class write implements Runnable
{
public void run()
{
Console cons = System.console();
while (true)
{
username = "[dgsgsdfg]: ";
System.out.print(username);
String input = cons.readLine();
String msg = username + input;
System.out.println(msg);
}
}
}
Code for read thread:
public static class read implements Runnable
{
public void run()
{
try
{
while(true)
{
Thread.sleep(5000);
for (int i = 0; i < username.length(); i++)
{
System.out.print("\b");
}
System.out.println("\n[qwerty]: hello");
System.out.print("[dgsgsdfg]: ");
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
P.S: The code show here is from a different program I created to try and fix this problem and it only contains the text printing part, and no networking or server stuff. The writer thread every 5 seconds prints hello, to simulate receiving and displaying a message.