繁体   English   中英

comm.jar通讯串口Java

[英]comm.jar communicating serial ports java

我在使用comm.jar时遇到问题。

问题是我已连接设备,并使用此代码在池中启动了应用程序

 public static void main(String[] args) {
        Enumeration portList;
        CommPortIdentifier portId = null;
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("port::" + portId.getName());

        }
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(JavaComPortFinding.class.getName()).log(Level.SEVERE, null, ex);
            }
            main(args);
        }
    }

输出:

port::COM1
port::COM10

经过一轮轮询后,我弹出了设备。 我仍然得到答复

port::COM1
port::COM10

谁能帮助我/建议在轮询中获得动态响应。

您可以尝试类似的操作,因为每次都应重新创建CommPortIdentifier。

class TestProgram
{
    public static void main(String[] args)
    {
        while(true)
        {
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException ex)
            {
                Logger.getLogger(TestProgram.class.getName()).log(Level.SEVERE, null, ex);
            }

            scanPorts();
        }
    }

    private static void scanPorts()
    {
        Enumeration portList;
        CommPortIdentifier portId = null;
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements())
        {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("port::" + portId.getName());

        }
    }
}

编辑:

我刚刚使用USB上的BlackBerry在Windows XP SP3上测试了该程序。 启动程序时,我看到了BlackBerry的普通COM1和两个COM端口。 断开BlackBerry后,端口将保留在设备管理器中。 如果我手动删除它们,它们将消失在程序中(无需重新启动)。

https://community.oracle.com/thread/2063873?start=0&tstart=0

在寻找类似问题的解决方案时,我发现上述资源极为宝贵。

这里的主要问题是CommPortIdentifier中的静态块仅加载一次,并将端口信息缓存在字段变量portList 调用getPortIdentifiers()方法时,它将从portList返回在初始加载期间检测到的端口。

解决方法是重新加载CommPortIdentifier类中的静态块,然后调用getPortIdentifiers() ,这将重新加载驱动程序并为您提供COM端口的更新列表(这是在引用的链接中使用Java Reflection API完成的)。

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM