package com.ehealth.util.measure.commport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import org.apache.log4j.Logger;
import com.ehealth.util.CommonUtil;
import com.ehealth.util.measure.commport.event.UartConnListener;
public abstract class UartConn {
private static final Logger logger = Logger.getLogger(UartConn.class);
private LinkedList<UartConnListener> listeners = new LinkedList<UartConnListener>();//添加监听事件放到LinkedList中
protected SerialPort serialPort;//串行端口
static OutputStream outputStream;//输出流
InputStream inputStream;//输入流
protected UartConn(String commPort, int baudrate, int stopBits, int parity) {//UartConn构造方法
try {
CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(commPort);//查找端口
serialPort = (SerialPort)commPortIdentifier.open("Mrdu", 100);//打开串口
outputStream = serialPort.getOutputStream();//获取输出流
inputStream = serialPort.getInputStream();//获取输入流
serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, stopBits, parity);//1,波特率2,字节标准数据位长度3,字节的停止位数4,奇偶校验检查协议
} catch (Exception ex) {
logger.error(String.format("commPort: %s, baudrate: %d", commPort, baudrate), ex);
}
}
//没有解析的数据添加到UartConnListener监听事件中
protected synchronized void fireDataAcquired(byte[] data) {
for (UartConnListener listener : listeners) {
listener.dataAcquired(this, data);
}
}
//添加监听事件
public synchronized void addListener(UartConnListener listener) {
listeners.add(listener);
}
//发送数据
public void sendData(byte[] pack) {
if (serialPort != null) {
try {
logger.info("发送数据包操作 -->" + CommonUtil.printStr(pack));
OutputStream output = serialPort.getOutputStream();//输出流
output.write(pack);//写出pack数据
output.flush();//更新
} catch (IOException e) {
logger.error("Send failed", e);
}
}
}
protected abstract void readCom();
}
为什么第一次连接成功了,第二次就不执行到这段代码。拔掉端口后丢失端口然后插上不执行此代码,无法接收数据