// 器,我的理解是独立开辟一个线程串口数据
static CommPortIdentifier portId; // 串口通信管理类
static Enumeration《?》 portList; // 有效连接上的端口的枚举
InputStream inputStream; // 从串口来的输入流
static OutputStream outputStream;// 向串口输出的流
static SerialPort serialPort; // 串口的引用
// 堵塞队列用来存放读到的数据
private BlockingQueue《String》 msgQueue = new LinkedBlockingQueue《String》();
@Override
/**
* SerialPort EventListene 的方法,持续端口上是否有数据流
*/
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 {
int numBytes = -1;
while (inputStream.available() 》 0) {

numBytes = inputStream.read(readBuffer);
if (numBytes 》 0) {
msgQueue.add(new Date() + “真实收到的数据为:-----”
+ new String(readBuffer));
readBuffer = new byte〔20〕;// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
} else {
msgQueue.add(“额------没有读到数据”);
}
}
} catch (IOException e) {
}
break;
}
}
/**
*
* 通过程序打开COM4串口,设置器以及相关的参数
*
* @return 返回1 表示端口打开成功,返回 0表示端口打开失败
*/
public int startComPort() {
// 通过串口通信管理类获得当前连接上的串口列表
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
// 获取相应串口对象
portId = (CommPortIdentifier) portList.nextElement();
System.out.println(“设备类型:---》” + portId.getPortType());
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/sanxing/article-64363-2.html
饮料不饮料酒不像酒的玩意
主席的话“人不犯我