我已经完成了从串行端口读取字节流的代码。问题是我无法测试代码,因为我没有与这些端口交互的设备。
我已经使用了模拟器,但是在运行代码和模拟器时没有任何反应。没有进展,也没有错误。
这是代码
class SimpleRead implements Runnable, SerialPortEventListener{
CommPortIdentifier portId;
Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
/**
* Method declaration
*
*
* @param args
*
* @see
*/
public void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
jTextArea1.setText("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
jTextArea1.setText("port " + defaultPort + " not found.");
}
}
/**
* Constructor declaration
*
*
* @see
*/
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
/**
* Method declaration
*
*
* @see
*/
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
/**
* Method declaration
*
*
* @param event
*
* @see
*/
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
jTextArea1.setText(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
注意:我使用的是 javax.comm 和 Netbeans IDE。谢谢你