java的com口通訊

jopen 9年前發布 | 1K 次閱讀 Java

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;

static Enumeration portList;  

InputStream inputStream;  

SerialPort serialPort;  

Thread readThread;  

public static void main(String[] args) {  

    String com="4";  
    if(args!=null&&args.length>=1)  
    com=args[0];  

    portList = CommPortIdentifier.getPortIdentifiers();  
    // 檢索系統串口  
    while (portList.hasMoreElements()) {  
        portId = (CommPortIdentifier) portList.nextElement();  

        /*如果端口類型是串口,則打印出其端口信息*/   
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {  
            System.out.println("------------------------");  
            System.out.println("系統可用串口: "+portId.getName());  
            System.out.println("------------------------");  
            // 指定COM口  
            if (portId.getName().equals("COM"+com)) {  
                System.out.println("找到COM"+com+"口,初始化...");  
                SimpleRead reader = new SimpleRead();  
            }else{  
                System.out.println("無法找到COM"+com+"口,請重新指定...");  
            }  
        }  
    }  
}  

public SimpleRead() {  
    try {  
    // 打開COM串口 2000 設置毫秒數 超時等待時間  

        serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);  
        System.out.println("COM口打開成功!");  

    } catch (PortInUseException e) {  
        System.out.println("端口被占用");  
    }  
    try {  
        inputStream = serialPort.getInputStream();  
        System.out.println("獲得輸入流...");  
    } catch (IOException e) {  
    }  
    //進行端口監聽 , 當事件發生自動調用 serialEvent方法  
    try {  
        serialPort.addEventListener(this);  
    } catch (TooManyListenersException e) {  
    }  
    serialPort.notifyOnDataAvailable(true);  

    //設置通訊位  
    try {  
        System.out.println("設置通訊位...");  
        serialPort.setSerialPortParams(115200,// 設置波特率  
                SerialPort.DATABITS_8,// 數據位數  
                SerialPort.STOPBITS_1,// 停止位  
                SerialPort.PARITY_NONE);// 奇偶位  
    } catch (UnsupportedCommOperationException e) {  
    }  

    // 啟動線程,監聽  
    readThread = new Thread(this);//線程負責每接收一次數據休眠20秒鐘  
    readThread.start();  
}  

public void run() {  
    try {  
        System.out.println("監聽...");  
        Thread.sleep(20000);//休息20秒  

    } catch (Exception e) {  
    }  
}  
// 處理偵聽到的串口事件  
public synchronized void serialEvent(SerialPortEvent event) {  
//    System.out.println("接收數據...\r\n");  

    switch (event.getEventType()) {  
    case SerialPortEvent.BI://BI - 通訊中斷.  
    case SerialPortEvent.OE://OE - 溢位錯誤.  
    case SerialPortEvent.FE://FE - 幀錯誤.  
    case SerialPortEvent.PE://PE - 奇偶校驗錯.  
    case SerialPortEvent.CD://CD - 載波檢測.  
    case SerialPortEvent.CTS://CTS - 清除發送.  
    case SerialPortEvent.DSR://DSR - 數據設備準備好.  
    case SerialPortEvent.RI://RI -  振鈴指示.  
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY://OUTPUT_BUFFER_EMPTY - 輸出緩沖區已清空  
        break;  
    case SerialPortEvent.DATA_AVAILABLE://DATA_AVAILABLE - 有數據到達  


        byte[] readBuffer = new byte[10000];  

        try {  
            //讀數據  
            while (inputStream.available() > 0) {  
                int numBytes = inputStream.read(readBuffer);  
            }  

            String str=new String(readBuffer);  
            if(str.equals("exit")){  
                inputStream.close();serialPort.close();  
            }  
            //輸出內容  
            System.out.println("<------開始------->");  
            System.out.println(str+"==============");  
            System.out.println("<------結束------->");  
            System.out.println("                    ");  
        } catch (IOException e) {  
        }  
        break;  
    }  
}  

} </pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!