Java Reference
In-Depth Information
Unfortunately, these methods only work properly if the port is owned by a Java
application and not by some other non-Java program. However, if a port is already
in use by a non-Java program, then an attempt to open it reveals that situation, as
explained next.
23.4.3 Opening ports
If a port is available, you take exclusive possession of it via one of the two
overloaded open() methods and then use the port for reading and writing to the
external device connected to that port. The CommPortIdentifier method
CommPort open (String ownerName, int timeout)
throws PortInUseException
takes possession of the port and passes it the name of the owning application. The
timeout parameter determines how long in milliseconds the method will block
while waiting for the port to become available.
For systems such as Unix where ports can be assigned a FileDescriptor ,
the following overloaded open() method is provided:
CommPort open (java.io.FileDescriptor fd)
throws UnsupportedCommOperationException
Below we show an example where ports are opened. If they are already owned
by some other application, a PortInUseException is caught. If the owner is
aJava program, it can be identified by the name given in the open() method;
otherwise there is no name available.
import javax.comm.*;
import java.util.*;
/** Check each port to see if it is open. **/
public class PortListOpen
{
public static void main (String[] args) {
Enumeration port - list = CommPortIdentifier.getPortIdentifiers ();
while (port - list.hasMoreElements ()) {
// Get the list of ports
CommPortIdentifier port - id = (CommPortIdentifier) port - list.nextElement ();
// Find each ports type and name
 
Search WWH ::




Custom Search