⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commportmanager.java

📁 源码为科学出版社出版的英文<java设计模式>(影印版)所用的所有例子程序
💻 JAVA
字号:
import java.util.*;
import javax.comm.*;

public class CommPortManager extends PortManager {
     
public static Enumeration getAllPorts() {
   CommPortIdentifier portId;
   Enumeration portEnum;

   Vector ports = new Vector();

   portEnum = CommPortIdentifier.getPortIdentifiers();

      while (portEnum.hasMoreElements()) {
          portId = (CommPortIdentifier) portEnum.nextElement();
          if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
             {
             ports.addElement (portId.getName());
             }
      }
      //add bogus port
      ports.addElement("COM5");
  return ports.elements ();   //return enumeration
 }
//-------------------------------------
public static Enumeration getAvailablePorts() {
   Vector portOpenList = new Vector();
   CommPortIdentifier portId;

   Enumeration enum = getAllPorts();
   while (enum.hasMoreElements ()) {
      String portName = (String)enum.nextElement () ;
      try {
         //try to get port ownership
         portId = CommPortIdentifier.getPortIdentifier(portName);
         //if successful, open the port
         CommPort cp = portId.open("SimpleComm",100);
         //report success
         portOpenList.addElement(portName);
         cp.close();
         }
      catch(NoSuchPortException e){}
      catch(PortInUseException e){}
    }
   return portOpenList.elements ();
 }
//-------------------------------------
public static CommPort openPort(String portName) {
   CommPortIdentifier portId;
 
   try {
      //try to get port ownership
      portId = CommPortIdentifier.getPortIdentifier(portName);
      //if successful, open the port
      CommPort cp = portId.open("SimpleComm",100);
      //report success
      return cp;
      }
   catch(NoSuchPortException e){
     return null;}
   catch(PortInUseException e){
     return null;}
   }
//-------------------------------------
public static CommPort openPort() {
   CommPortIdentifier portId;
   
   Enumeration enum = getAvailablePorts();
   if (enum.hasMoreElements ()) {
     String portName = (String)enum.nextElement ();
     try {
      portId = CommPortIdentifier.getPortIdentifier(portName);
      CommPort cp = portId.open("SimpleComm",100);
      //report success
      return cp;
      }
   catch(NoSuchPortException e){return null;}
   catch(PortInUseException e){return null;}
  }
 else
   return null;
 }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -