基本信息
源码名称:串口通讯实例(java swing)
源码大小:0.36M
文件格式:.zip
开发语言:Java
更新时间:2021-09-26
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 4 元 
   源码介绍

实现了,多个监听多个串口设备连接

 public void init(ParamConfig paramConfig, CallBackInterface callback) throws Exception {
    this.callBackFun = callback;
    this.paramConfig = paramConfig;
        // 获取系统中所有的通讯端口
        portList = CommPortIdentifier.getPortIdentifiers();
        // 记录是否含有指定串口
        boolean isExsist = false;
        // 循环通讯端口
        while (portList.hasMoreElements()) {
            commPortId = portList.nextElement();
            // 判断是否是串口
            if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 比较串口名称是否是指定串口
                if (paramConfig.getSerialNumber().equals(commPortId.getName())) {
                    // 串口存在
                    isExsist = true;
                    // 打开串口
                    try {
                        // open:(应用程序名【随意命名】,阻塞时等待的毫秒数)
                        serialPort = (SerialPort) commPortId.open(Object.class.getSimpleName(), 2000);
                        // 设置串口监听
                        serialPort.addEventListener(this);
                        // 设置串口数据时间有效(可监听)
                        serialPort.notifyOnDataAvailable(true);
                        // 设置串口通讯参数:波特率,数据位,停止位,校验方式
                        serialPort.setSerialPortParams(paramConfig.getBaudRate(), paramConfig.getDataBit(),
                                paramConfig.getStopBit(), paramConfig.getCheckoutBit());
                    } catch (PortInUseException e) {
                        try {
throw new CustomException("端口被占用");
} catch (CustomException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
                    } catch (TooManyListenersException e) {
                        try {
throw new CustomException("监听器过多");
} catch (CustomException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
                    } catch (UnsupportedCommOperationException e) {
                        try {
throw new CustomException("不支持的COMM端口操作异常");
} catch (CustomException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
                    }
                    // 结束循环
                    break;
                }
            }
        }
        // 若不存在该串口则抛出异常
        if (!isExsist) {
            try {
throw new CustomException("不存在该串口!");
} catch (CustomException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
    }