Java Reference
In-Depth Information
To summarize, the basic steps in using a communications port are as follows:
getPortIdentifiers()
, and choose the port you want.
2. Call the
CommPortIdentifier
's
open()
method; cast the resulting
CommPort
object
to a
SerialPort
object or
ParallelPort
as appropriate.
3. Set the communications parameters (i.e., baud rate, parity, stop bits, and the like),
either individually or all at once, using the convenience routine
setSeri-
alPortParams()
for a serial port or “mode” for a parallel port.
4. Call the
getInputStream
and
getOutputStream
methods of the
CommPort
object,
You are then ready to read and write on the port.
Example 10-13
is code that implements all
these steps for a serial port. For parallel ports the API is similar; consult the online docu-
mentation.
Example 10-13. src/main/java/javacomm/CommPortSimple.java
/**
* Open a serial port using Java Communications.
* @author Ian F. Darwin, http://www.darwinsys.com/
*/
public
public class
class
CommPortSimple
CommPortSimple
{
private
private static
final
String HELLO
=
"Hello?"
;
/** How long to wait for the open to finish up. */
public
static final
public static
int
TIMEOUTSECONDS
=
30
;
/** The baud rate to use. */
public
static final
final
int
public static
int
BAUD
=
19200
;
/** The input stream */
protected
static final
final
int
protected
BufferedReader is
;
/** The output stream */
protected
protected
PrintStream os
;
/** The chosen Port Identifier */
CommPortIdentifier thePortID
;
/** The chosen Port itself */
CommPort thePort
;
public
public static
static
void
void
main
(
String
[]
argv
)
throws
throws
Exception
{
iif
(
argv
.
length
!=
1
) {