#10: Java can't talk to the serial and parallel ports
The Java Communications API is a very straight-forward API to talk
to the serial and parallel ports.
- A standard extension to Java 1.2.
- Available on Mac, Windows, and some Unixes (Solaris).
- It's a very low-level API. There are no content or protocol handlers as there
are with the URL classes. It's even lower level than the Socket classes.
You just send and receive raw bytes to and from the port.
You're reponsible for speaking HPCL or the Hayes AT command set
or whatever protocol you need to speak.
- Only serial and parallel ports are supported. USB, Firewire, etc. are still needed.
import javax.comm.*;
import java.util.*;
import java.io.*;
public class PortTyper {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PortTyper portName");
return;
}
try {
CommPortIdentifier com =
CommPortIdentifier.getPortIdentifier(args[0]);
CommPort thePort = com.open("PortOpener", 10);
CopyThread input =
new CopyThread(System.in, thePort.getOutputStream());
CopyThread output =
new CopyThread(thePort.getInputStream(), System.out);
input.start();
output.start();
}
catch (Exception e) {
System.out.println(e);
}
}
}
class CopyThread extends Thread {
InputStream theInput;
OutputStream theOutput;
CopyThread(InputStream in) {
this(in, System.out);
}
CopyThread(OutputStream out) {
this(System.in, out);
}
CopyThread(InputStream in, OutputStream out) {
theInput = in;
theOutput = out;
}
public void run() {
try {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = theInput.read(buffer);
if (bytesRead == -1) break;
theOutput.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
Still need
Previous | Next | Top
Other Presentations
| Cafe au Lait Home
Last Modified May 16, 1999
Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu