我在CommPortIdentifier.getPortIdentifier()上读到串行ports.when程序时遇到了问题,它被卡住了将近5分钟。据我观察,延迟可能是由于扫描系统中的所有端口造成的。那么如何避免这5分钟的延迟呢?
发布于 2011-02-24 22:40:28
如何扫描可用端口?
例如,以下代码将返回可用串行端口的字符串列表:
public List<String> getAvailablePorts() {
List<String> list = new ArrayList<String>();
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
list.add(portId.getName());
}
}
return list;
}编辑:因为实际的解决方案是在注释中挖掘出来的,所以我在这里添加:
在某些情况下,commPortIdentifier.getPortIdentifier(portName)似乎确实会重新扫描端口;快速解决方法是通过gnu.io.rxtx.SerialPorts系统属性手动设置固定端口列表。
发布于 2015-08-07 02:08:52
这可能不适用于所有情况,但它对我有效,它只需要不到一秒钟的时间就可以获得我想要的端口。我从命令行开始使用Windows的devcon实用程序。
devcon find "usb\vid_067B&PID_2303*"这将列出连接多产PL2303 USB串行电缆的端口。然后我解析了结果。我通常得到的结果很少,因为我只在我的计算机上插入一到两根电缆。
这段代码可能不是可移植的和有限的,但它非常适合我的目的,而且它的速度比使用CommPortIdentifier.getPortIdentifiers()快得多。
下面是我的代码的一部分:
public List<String> getAvailablePorts() {
List<String> list = new ArrayList<String>();
String res="";
BufferedReader br;
String cmd;
Process proc;
try {
/*search for ports where Prolific PL2303 cable is attached*/
cmd = "devcon find \"usb\\vid_067B&PID_2303*\"";
proc = Runtime.getRuntime().exec(cmd);
/* parse the command line results*/
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
do {
try {
res = br.readLine();
if (res == null)
break;
if (res.contains((CharSequence)("Prolific USB")))
list.add(res.substring(res.indexOf("(COM")+1, res.indexOf(")")));
} catch(Exception e) {
e.printStackTrace();
}
} while (!res.equals("null"));
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return list;
}只需确保devcon.exe文件是正确的(32位或64位),并且它位于应用程序可以访问它的正确文件夹中。
这在64位WinXP和Win7/8上有效,但对于32位Win7/8,应用程序可能需要以管理员权限启动(以管理员身份运行)。我在最终的可执行文件中添加了一个.manifest文件,这样就不需要在32位Windows上“右键单击并以管理员身份运行”。
在Ubuntu 14.04 Linux上,我使用了终端命令
ls /dev/ttyUSB*列出USB-Serial端口,然后解析结果。
https://stackoverflow.com/questions/5105857
复制相似问题