0

i'm currently developing a chat server with java and sockets in the terminal, and it works fine, we can send messages and receive messages. The problem is if we are in the middle of writing a sentence and another message is received it interrupts the message being written, for example:

   ClientA is writing "hello World"
   ClientB ,before ClientA can send his message, send his own "hello there"
   ClientA gets the result "hello Worldhello there" in its terminal, instead of being able to send his message and than receiving ClientB message.

I`m using separate threads for reading incoming messages and writing new ones, can i use Reentrant locks to avoid receiving messages mid writing one?

Send message code:

while((userInput = systemIn.readLine()) != null && !userInput.equals("quit")) 
            {
                    out.println(userInput);
                    out.flush();
            }

Read message code:

while((message = in.readLine()) != null )
            {

                System.out.println(message);
            }

  • Honestly you need to rethink using the system streams for writing and showing messages. In other words, what you are doing is needlessly complicated, and you should build a GUI of some kind where you can do all this in a nicer way. – ControlAltDel May 14 '20 at 17:38
  • 1
    The only time when one is not writing a message (i,e, when one is not waiting for a message to be typed) is when you're writing the message to output. You can't reliably do what you want to do using `readLine`. – Burak Serdar May 14 '20 at 17:47
  • thanks for the comments and attention. – Manuel0Borba May 14 '20 at 17:57

0 Answers0