我使用RXTXcomm Library连接COM端口
如果COM端口连接在应用程序运行时(物理上)丢失
我不知道Port是否连接。
当COM端口物理断开时,即使信号仍然存在。
我如何检测COM端口连接丢失??
这里是我的代码
public class SerialSample implements SerialPortEventListener{
private InputStream in;
private OutputStream out;
public SerialSample() {
super();
}
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
//System.out.println("connect");
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
@Override
public synchronized void serialEvent(SerialPortEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE){
try{
int a = in.available();
byte chunk[] = new byte[a];
in.read(chunk, 0, a);
System.out.println(new String(chunk) + " , " + a);
inputSignal();
}catch(Exception e){
System.out.println(e.toString());
}
}
}