JAVA rs232 全套资源提供
全套项目资源环境都在我发布的资源里
环境
Configure Virtual Serial Port Driver 模拟串口
友善串口工具调试
MAVEN 依赖
<dependency>
<groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
<artifactId>rxtxcomm</artifactId>
<version>2.2</version>
</dependency>
代码贴出
import com.runyao.vending.exception.CustomException;
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class RxtxUtil extends Thread implements SerialPortEventListener {
private CommPortIdentifier portId; // 串口通信管理类
private Enumeration<?> portList; // 有效连接上的端口的枚举
private InputStream inputStream; // 从串口来的输入流
private OutputStream outputStream;// 向串口输出的流
private SerialPort serialPort; // 串口的引用
// 堵塞队列用来存放读到的数据
private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
public RxtxUtil(String portName, int baudRate) {
this.startComPort(portName,baudRate);
this.start();
}
/**
* SerialPort EventListene 的方法,持续监听端口上是否有数据流
*/
@Override
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[1024];
try {
int numBytes = -1;
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
if (numBytes > 0) {
msgQueue.add(new String(readBuffer, "gbk"));
readBuffer = new byte[1024];// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
}
}
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
/**
* 通过程序打开串口,设置监听器以及相关的参数
*
* @return 返回1 表示端口打开成功,返回 0表示端口打开失败
*/
private void startComPort(String portName,int baudRate) {
// 通过串口通信管理类获得当前连接上的串口列表
portList = CommPortIdentifier.getPortIdentifiers();
// 记录是否含有指定串口
boolean isExsist = false;
while (portList.hasMoreElements()) {
// 获取相应串口对象
portId = (CommPortIdentifier) portList.nextElement();
// 判断端口类型是否为串口
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// 判断如果COM7串口存在,就打开该串口
if (portId.getName().equals(portName)) {
isExsist=true;
try {
// 打开串口,延迟为2毫秒
serialPort = (SerialPort) portId.open(portName, 2000);
// 设置当前串口的输入输出流
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
// 给当前串口添加一个监听器
serialPort.addEventListener(this);
// 设置监听器生效,即:当有数据时通知
serialPort.notifyOnDataAvailable(true);
// 比特率、数据位、停止位、奇偶校验位
serialPort.setSerialPortParams(baudRate,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_EVEN);
} catch (PortInUseException e) {
throw new CustomException("端口被占用");
} catch (TooManyListenersException e) {
throw new CustomException("监听器过多");
} catch (UnsupportedCommOperationException e) {
throw new CustomException("不支持的COMM端口操作异常");
} catch (IOException e) {
throw new CustomException("获取流异常");
}
}
}
}
// 若不存在该串口则抛出异常
if (!isExsist) {
throw new CustomException("不存在该串口!");
}
}
/**
* 发送信息
* @param message
*/
public void sendMessage(String message) {
try {
outputStream.write(message.getBytes("gbk"));
outputStream.flush();
} catch (NullPointerException e) {
throw new CustomException("找不到串口。");
} catch (IOException e) {
throw new CustomException("发送信息到串口时发生IO异常");
}
}
/**
* 关闭串口
*/
public void closeSerialPort() {
if (serialPort != null) {
serialPort.notifyOnDataAvailable(false);
serialPort.removeEventListener();
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
throw new CustomException("关闭输入流时发生IO异常");
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
throw new CustomException("关闭输出流时发生IO异常");
}
}
serialPort.close();
serialPort = null;
}
}
//处理返回后的消息
@Override
public void run() {
try {
System.out.println("--------------任务处理线程运行了--------------");
while (true) {
// 如果堵塞队列中存在数据就将其输出
if (msgQueue.size() > 0) {
System.out.println(msgQueue.take());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
发送消息
RxtxUtil com1 = new RxtxUtil("COM1", 9600);
com1.sendMessage("aaaa");