Question

I have Java application. I try to realize multiplayer chat with TCP protocol, but I have an issue. I cannot output all messages I get on client tier (server tier works perfectly), because I give an input to user and create a thread to read messages from TCP client, so

<Scanner object>.nextLine();

Is blocking an output of my app. I can create by Swing, but I still haven't fully understood it.

I have two options:

  1. Output all new messages from queue after sending message by user.
  2. Somehow detach input and output.

I think you don't need to explain that in 1st option if user will go out for a long time, he will need to send a message before he will get all these new messages.

Only the second option remains. I need to detach input and output and I found that in some "interactive tasks" there are two consoles - first used for input, other - for output. But can I do it into a Java? And if I can, how?

Was it helpful?

Solution

If you use Swing, you can make the traditional two-control "chat" layout: ┌────────────┐ │output │ │output │ │output │ │... │ └────────────┘ ┌────────────┐ │input> _ │ └────────────┘

Send one thread to output to the top area, another thread to listen to changes in the bottom area. You can send bottom area's contents to the top area, too, if you want an unified log. You will need line-level buffering, though, like traditional terminals have; they hae it for a reason. Without it, parts of lines would intermix.

If you want Linux / macOS / other posix console, use some wrapper around curses to reproduce the layout like above, and don't read stdin directly.

(If you need Windows console, I have no idea what to use.)

Licensed under: CC-BY-SA with attribution
scroll top