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

📄 serialconnection_new.java

📁 利用JAVA采用网络通讯的例子,支持weblogic及websphere
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package collector.communication;

/* @(#)SerialConnection_new.java	1.6 98/07/17 SMI
 *
 * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license
 * to use, modify and redistribute this software in source and binary
 * code form, provided that i) this copyright notice and license appear
 * on all copies of the software; and ii) Licensee does not utilize the
 * software in a manner which m_InputStream disparaging to Sun.
 *
     * This software m_InputStream provided "AS IS," without a warranty of any kind.
 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
 * SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
 * BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
 * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
 * OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * This software m_InputStream not designed or intended for use in on-line control
 * of aircraft, air traffic, aircraft navigation or aircraft
 * communications; or in the design, construction, operation or
 * maintenance of any nuclear facility. Licensee represents and
 * warrants that it will not use or redistribute the Software for such
 * purposes.
 */

import java.io.*;
import javax.comm.*;

import collector.common.*;

/**
 * A class that handles the details of a serial connection. Reads from one
 * TextArea and writes to a second TextArea.
 * Holds the state of the connection.
 */
public class SerialConnection_new
    implements SerialPortEventListener, CommPortOwnershipListener, IComm {
  private SerialParameters m_SerialParameters = null;
  private OutputStream m_OutputStream = null;
  private InputStream m_InputStream = null;
  //private KeyHandler keyHandler;

  private CommPortIdentifier m_PortId = null;
  private SerialPort m_Port = null;
  private int m_PortNo = -1;
  private BufferStream m_BufferStream = null;
//  private byte[] m_RecBuffer = null;
//  private int m_RecNum = 0;

  private boolean m_Open = false;

  /**
   * Creates a SerialConnection_new object and initilizes variables passed in
   * as params.
   *
   * @param parent A SerialDemo object.
   * @param m_SerialParameters A SerialParameters object.
   * @param messageAreaOut The TextArea that messages that are to be sent out
   * of the serial port are entered into.
   * @param messageAreaIn The TextArea that messages comming into the serial
   * port are displayed on.
   */
  public SerialConnection_new( /*SerialDemo parent,*/
      SerialParameters m_SerialParameters
      /*TextArea messageAreaOut,
                              TextArea messageAreaIn*/) {
    /*	this.parent = parent;*/
    this.m_SerialParameters = m_SerialParameters;
    this.m_BufferStream = new BufferStream();

    /*	this.messageAreaOut = messageAreaOut;
        this.messageAreaIn = messageAreaIn;
     */
    this.m_Open = false;
  }

  /**
   * Attempts to m_Open a serial connection and streams using the m_SerialParameters
   * in the SerialParameters object. If it m_InputStream unsuccesfull at any step it
   * returns the port to a closed state, throws a
   * <code>SerialConnection_newException</code>, and returns.
   *
   * Gives a timeout of 30 seconds on the portOpen to allow other applications
   * to reliquish the port if have it m_Open and no longer need it.
   */

  public int setPortId(CommPortIdentifier m_PortId) {
    this.m_PortId = m_PortId;
    return 1;
  }

  public int initConnection() {
    // Obtain a CommPortIdentifier object for the port you want to m_Open.
    //CollectorDefine.SystemPrintln ("  serial initConnnection start up!!!  ");
    try {
      this.m_PortId =
          CommPortIdentifier.getPortIdentifier(m_SerialParameters.getPortName());
    }
    catch (NoSuchPortException e) {
      //	    throw new ConnectionException(e.getMessage());
      CFunction.putHintString(1,
                              "无此端口 " + "端口号:" + m_SerialParameters.getPortName());
      return -1;
    }

    // Open the port represented by the CommPortIdentifier object. Give
    // the m_Open call a relatively long timeout of 30 seconds to allow
    // a different application to reliquish the port if the user
    // wants to.
    try {
      this.m_Port = (SerialPort) m_PortId.open(CFunction.getLocalHostName() +
                                               "_App", 30000);
    }
    catch (PortInUseException e) {
      //	    throw new ConnectionException(e.getMessage());
      CFunction.putHintString(1,
                              "端口已占用 " + "端口号:" +
                              m_SerialParameters.getPortName());

      // wj add
      // Close the port.
      this.m_Port.close();
      this.m_Open = false;
      //

      return -1;
    }

    // Set the m_SerialParameters of the connection. If they won't set, close the
    // port before throwing an exception.
    try {
      if (setConnectionParameters(this.m_SerialParameters) <= 0) {
        CFunction.putHintString(1,
                                "端口参数错 " + "端口号:" +
                                m_SerialParameters.getPortName());
        this.m_Port.close();
        this.m_Open = false;
        return -1;
      }
    }
    catch (Exception m_Exception) {
      CFunction.putHintString(1,
          "setConnectionParameters In SerialConnection_new Error #1 ");
      return -1;
    }

    // Open the input and output streams for the connection. If they won't
    // m_Open, close the port before throwing an exception.
    try {
      this.m_OutputStream = this.m_Port.getOutputStream();
      this.m_InputStream = m_Port.getInputStream();
    }
    catch (IOException e) {
      this.m_Port.close();
      this.m_Open = false;
      //	    throw new ConnectionException("Error opening i/o streams");
      CFunction.putHintString(1,
                              "打开数据流出错 " + "端口号:" +
                              m_SerialParameters.getPortName());

      return -1;
    }

    // Create a new KeyHandler to respond to key strokes in the
    // messageAreaOut. Add the KeyHandler as a keyListener to the
    // messageAreaOut.
    /*	keyHandler = new KeyHandler(m_OutputStream);
            messageAreaOut.addKeyListener(keyHandler);
     */

    // Add this object as an event listener for the serial port.
    // wj add at hangzhou 20040528
    try {
      this.m_Port.addEventListener(this);
    }
    //catch (TooManyListenersException e)
    catch (Exception e) {
      m_Port.close();
      this.m_Open = false;
      //	    throw new ConnectionException("too many listeners added");
      CFunction.putHintString(1,
                              "端口监听器太多 " + "端口号:" + m_SerialParameters.getPortName());
      return -1;
    }

    this.m_Port.notifyOnDataAvailable(true);

    this.m_Port.notifyOnBreakInterrupt(true);
    this.m_Port.notifyOnCarrierDetect(true);
    this.m_Port.notifyOnCTS(true);
    this.m_Port.notifyOnDSR(true);
    this.m_Port.notifyOnFramingError(true);
    this.m_Port.notifyOnOutputEmpty(true);
    this.m_Port.notifyOnOverrunError(true);
    this.m_Port.notifyOnRingIndicator(true);
    this.m_Port.notifyOnParityError(true);
    // wj add at hangzhou 20040528

    // Set receive timeout to allow breaking out of polling loop during
    // input handling.
    try {
      this.m_Port.enableReceiveTimeout(30);
    }
    catch (UnsupportedCommOperationException e) {
      CFunction.putHintString(1,
          "setConnectionParameters In SerialConnection_new Error #2 ");

      // wj add at hangzhou 20040528
      this.m_Port.removeEventListener();
      m_Port.close();
      this.m_Open = false;
      // wj add at hangzhou 20040528

      return -1;
    }

    // wj add at hangzhou 20040528
    // Add ownership listener to allow ownership event handling.
    this.m_PortId.addPortOwnershipListener(this);
    // wj modi at hangzhou 20040528

    m_Open = true;
    return 1;
  }

  /**
   * Sets the connection m_SerialParameters to the setting in the m_SerialParameters object.
       * If set fails return the m_SerialParameters object to origional settings and
   * throw exception.
   */
  public int setConnectionParameters(SerialParameters m_SerialParameters) {
    // Save state of m_SerialParameters before trying a set.
    //CollectorDefine.SystemPrintln ("fffffffff : " + m_SerialParameters.toString ());
    int oldBaudRate = m_Port.getBaudRate();
    int oldDatabits = m_Port.getDataBits();
    int oldStopbits = m_Port.getStopBits();
    int oldParity = m_Port.getParity();
    int oldFlowControl = m_Port.getFlowControlMode();

    //CollectorDefine.SystemPrintln ("gggggggg : " + m_SerialParameters.toString ());
    this.m_SerialParameters = m_SerialParameters;
    //CollectorDefine.SystemPrintln ("hhhhhhhhh : " + m_SerialParameters.toString ());

    // Set connection m_SerialParameters, if set fails return m_SerialParameters object
    // to original state.
    try {
      m_Port.setSerialPortParams(m_SerialParameters.getBaudRate(),
                                 m_SerialParameters.getDatabits(),
                                 m_SerialParameters.getStopbits(),
                                 m_SerialParameters.getParity());
      //CollectorDefine.SystemPrintln ("iiiiii : " + m_SerialParameters.toString ());
    }
    catch (UnsupportedCommOperationException e) {
      //CollectorDefine.SystemPrintln ("jjjjjjjjj : " + m_SerialParameters.toString ());
      this.m_SerialParameters.setBaudRate(oldBaudRate);
      this.m_SerialParameters.setDatabits(oldDatabits);
      this.m_SerialParameters.setStopbits(oldStopbits);
      this.m_SerialParameters.setParity(oldParity);
      //	    throw new ConnectionException("Unsupported parameter");
      CFunction.putHintString(1,
                              "端口参数不支持 " + "端口号:" +
                              m_SerialParameters.getPortName());
      return -1;
    }

    // Set flow control.
    try {
      //CollectorDefine.SystemPrintln ("kkkkkkkkkk : " + m_SerialParameters.toString ());
      m_Port.setFlowControlMode(m_SerialParameters.getFlowControlIn()
                                | m_SerialParameters.getFlowControlOut());
    }
    catch (UnsupportedCommOperationException e) {
      //	    throw new ConnectionException("Unsupported flow control");
      CFunction.putHintString(1,
                              "端口流控制参数不支持 " + "端口号:" +
                              m_SerialParameters.getPortName());
      return -1;
    }

    //CollectorDefine.SystemPrintln ("lllllll : " + m_SerialParameters.toString ());
    return 1;
  }

  /**
   * Close the port and clean up associated elements.
   */
  public int closeConnection() {
    // If port m_InputStream alread closed just return.
    if (!m_Open) {
      CFunction.putHintString(1,
                              "closeConnection In SerialConnnection  " + "端口号:" +
                              m_SerialParameters.getPortName());
      return -1;
    }

    // Remove the key listener.
    /*messageAreaOut.removeKeyListener(keyHandler);*/
    // Check to make sure m_Port has reference to avoid a NPE.
    if (m_Port != null) {
      try {
        //close the i/o streams.
        //m_InputStream.reset ();
        this.m_OutputStream.close();
        this.m_InputStream.close();

        //close the port.
        this.m_Port.close();


        // wj add at hangzhou 20040529
        this.m_BufferStream.close();
        this.m_BufferStream = null;

        this.m_OutputStream = null;
        this.m_InputStream = null;
        this.m_Port = null;
        // wj add at hangzhou 20040529
      }
      catch (IOException e) {
        CFunction.putHintString(1,
                                "closeConnection In SerialConnection_new Error #1 ");
        System.err.println(e);
        return -1;
      }

      // wj add at hangzhou 20040528
      // Remove the ownership listener.
      this.m_PortId.removePortOwnershipListener(this);
      // wj add at hangzhou 20040528
    }

    m_Open = false;
    return 1;
  }

  /**
   * Send a one second break signal.
   */
  public int sendBreak() {
    m_Port.sendBreak(1000);

    return 1;
  }

  /**
   * Reports the m_Open status of the port.
       * @return true if port m_InputStream m_Open, false if port m_InputStream closed.
   */
  public boolean isConnectionOpen() {
    return m_Open;
  }

  /**
   * Handles SerialPortEvents. The two types of SerialPortEvents that this
   * program m_InputStream registered to listen for are DATA_AVAILABLE and BI. During
   * DATA_AVAILABLE the port buffer m_InputStream read until it m_InputStream drained, when no more
       * data m_InputStream availble and 30ms has passed the method returns. When a BI
   * event occurs the words BREAK RECEIVED are written to the messageAreaIn.
   */

  public void serialEvent(SerialPortEvent e) {
    //Create a StringBuffer and int to receive input data.
    //StringBuffer inputBuffer = new StringBuffer();
    int newData = 0;
    // Determine type of event.
    switch (e.getEventType()) {

      // Read data until -1 m_InputStream returned. If \r m_InputStream received substitute
      // \n for correct newline handling.
      case SerialPortEvent.DATA_AVAILABLE:
        while (newData != -1) {
          try {
            newData = m_InputStream.read();
            if (newData == -1) {
              //CollectorDefine.SystemPrintln ("rec no byte ");
              break;
            }
            if ('\r' == (char) newData) {
              CollectorDefine.SystemPrintln("rec r");
            }
            else {
              //CollectorDefine.SystemPrintln ("rec byte ");
              //CollectorDefine.SystemPrintln ("rec byte ," +"len :" + newData);

              this.m_BufferStream.write(newData);
            }
          }
          catch (IOException ex) {
            System.err.println(ex);
            return;
          }
        }

        break;

      case SerialPortEvent.BI:
        CFunction.putHintString(1, "BI event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.CTS:
        CFunction.putHintString(1, "CTS event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.CD:
        CFunction.putHintString(1, "CD event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.DSR:
        CFunction.putHintString(1, "DSR event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.FE:
        CFunction.putHintString(1, "FE event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.OE:
        CFunction.putHintString(1, "OE event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;
      case SerialPortEvent.PE:
        CFunction.putHintString(1, "PE event occcured." + "端口号:" +
                                m_SerialParameters.getPortName());

        break;

⌨️ 快捷键说明

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