After the connection is made, you don’t know what order to read or write in.
Use a thread to handle each direction.
When you have two things that must happen at the same time or
unpredictably, the normal Java paradigm is to use a thread for each.
We will discuss threads in detail in Chapter 24,
but for now, just think of a thread as a small, semi-independent flow
of control within a program, just as a program is a small,
self-contained flow of control within an operating system. The Thread
API requires you to construct a method whose signature is
to do the body of work for the thread,
and call the
method of the thread to
“ignite” it and start it running independently. This
example creates a
Thread subclass called
DataThread, which reads from one file and writes
works a byte at a time so that it
will work correctly with interactive prompts, which don’t end
at a line ending. My now-familiar
method creates two of these
DataThreads, one to handle data
“traffic” from the keyboard to the remote, and one to
handle bytes arriving from the remote and copy them to the standard
output. For each of these the
start( ) method is
called. Example 11-9 shows the
Example 11-9. CommPortThreaded.java
import java.io.*; import javax.comm.*; import java.util.*; /** * This program tries to do I/O in each direction using a separate Thread. */ public class CommPortThreaded ...