I am trying to make a very simple chat program between two computers (server and client) using Java's UDP DatagramSockets and DatagramPackets.
While they are able to successfully send messages to each other and print the messages on each other's terminal, a limitation I found was that if I am in the middle of writing something and there is an incoming message, my own typing will get cut off. This is due to using print statements to display the incoming messages on the terminal. An example:
I am wondering if there are any kind of tools, frameworks or even ways of getting terminal input that can help to prevent this kind of display cut off of sentences we are typing.
CodePudding user response:
There exist frameworks that emulate "smart" terminals like the VT100. (The VT100 used to be considered pretty smart back in its hay-day, some 50 years ago.) Once you have such a terminal emulator, you will be able to position the cursor anywhere you want within the terminal window, (the screen of the terminal,) either by calling methods of some class, or by emitting ANSI escape sequences (look it up) and any text you write to the terminal will be written at the position of the cursor, so you will be able to keep the outgoing text separate from the incoming text.
A google search for "vt100 emulator for java" yields several results, the first one being on GitHub, (so, full source code available,) and is by none other than JetBrains, the company that makes the pretty awesome IntelliJ IDEA IDE.
However, I would advice against doing that, because your chat application will be clunky and it will have a look and feel that will resemble the seventies.
You will be much better off using java's built-in graphics system (AWT/Swing) to create a simple window with two text areas, one for the incoming text, and one for the outgoing text. There are many (I mean, many) instances of sample code floating out there on the great interwebz for doing pretty much about anything using Swing, so you should probably be able to even find a ready-to-run sample chat application in Java using Swing out there.