Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

sockets - how to count Usb port using java?

I want to detect list of USB Ports which are free (not occupied) in system to while I checked with CommPortIdentifier.getPortIdentifiers() while this returns me Enumeration with 0 elements I'd add librxtxcomm.jar too in classpath.

This should return each Port detail

Enumeration pList = CommPortIdentifier.getPortIdentifiers(); 
System.out.println(pList.hasMoreElements());

this returns 0 mean no List/Enumeration.

Rest Code :

public class CommPortLister{

    /** Simple test program. */
    public static void main(String[] ap) {
        new CommPortLister().list();
    }

    /** Ask the Java Communications API * what ports it thinks it has. */
    protected void list() {
        // get list of ports available on this particular computer, by calling static method in CommPortIdentifier.

        System.out.println("");
        Enumeration pList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("Before While");
        // CommPortIdentifier.getPortIdentifiers(); 
        // Process the list.
        System.out.println(pList.hasMoreElements());

        while (pList.hasMoreElements()) {
            System.out.println("While Loop");
            CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
            System.out.print("Port " + cpi.getName() + " ");
            if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("is a Serial Port: " + cpi);
            } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL)  {
                System.out.println("is a Parallel Port: " + cpi);
            } else  {
                System.out.println("is an Unknown Port: " + cpi);
            }
        }
        System.out.println("After While");
    }
}

Code to detect USB port while i am unable to detect USB Port

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please try using ServerSocket(portNo). If there is an service running in the port, it will error so catch the exception and try the next port.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...