java 串口通信

背景

由于最近在做一個交通雷達項目藏斩,必須要接觸到串口通信娇哆,將雷達的數(shù)據(jù)不斷接收并處理馋艺,摸爬滾打了幾天嚎卫,淺顯的談談串口通信是什么已經(jīng)怎么去使用java串口通信嘉栓。

環(huán)境

剛接觸到串口通信時拿到的資料以及jar包是98年的javacomm20-win32.zip
由于發(fā)布時所適應的platform和JDK環(huán)境都已經(jīng)難以匹配,故改用RXTX下載點擊拓诸,
使用RXTX侵佃,和javacomm20基本是兼容的,除了引用的包有所不同奠支,所以馋辈,在commapi(javacomm20-win32.zip)sample中給出的demo關于怎樣去連接串口,讀寫數(shù)據(jù)都還可以使用倍谜,只需要import改為RXTX相應的包迈螟,即IO包,也可以使用快捷鍵快速修改尔崔,在eclipse是shift+Ctrl+O答毫,功能就是自動整理所import的包。
對于RXTX包的引入季春,還是有幾點需要說明的洗搂。當然這些點在官方doc中都是有說明的:

Windows
----------------------------------------------------
Choose your binary build - x64 or x86 (based on which version of
the JVM you are installing to)

NOTE: You MUST match your architecture.  You can't install the i386
version on a 64-bit version of the JDK and vice-versa.

For a JDK installation:

Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin
Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin

說明

串口通信是指在計算機連接了一些物理設備,設備可以通過連接電腦的串口(一般是RS-232,或轉為USB-232)來傳輸數(shù)據(jù)蚕脏,傳輸數(shù)據(jù)是雙向的侦副,既可以讀也可以寫侦锯。

雷達和PC的連接關系

所以驼鞭,對于Starter來說,一般會通過代碼去了解怎樣讀取所用PC的串口號以及怎樣連接此串口并讀取物理設備通過串口發(fā)送來的數(shù)據(jù)尺碰。話不多說挣棕,看代碼:

/**
 * 雷達參數(shù)設置
 */

package com.jky.radar;

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.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

/**
 * 
 * @author edit WENTAO_Wanna
 * @author  original kotkis
 */
/* 串口監(jiān)聽 */
public class INT1 extends javax.swing.JFrame implements SerialPortEventListener {

    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    static SerialPort serialPort;
    Thread readThread;

    static OutputStream outputStream;
    int radix = 16;
    String txt;

    ObjectInputStream inputFromClient;
    ObjectOutputStream outputToClient;

    String output = "";
    // 數(shù)據(jù)幀數(shù)
    int groupNums = 0;
    //用于存儲接收的數(shù)據(jù)
    ArrayList outputData = new ArrayList();

    public MSComm() {

        // Creat Server,作為服務器端發(fā)送數(shù)據(jù)
        try {
            // Creat a Server Socket
            ServerSocket serverSocket = new ServerSocket(8000);
            System.out.println("Server Started!");

            // Creat data input and output streams      
            // inputFromClient = new ObjectInputStream(socket.getInputStream());

            // Listen for a connection request
            Socket socket = serverSocket.accept();
            outputToClient = new ObjectOutputStream(socket.getOutputStream());
        
            /*while (true) {
                // Receive param from the Client
                // TODO
                
            }*/
        }
        catch (IOException e) {
            System.err.println(e);
        }
        
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed"
    // desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        defPane = new javax.swing.JFrame();
        defPane.setSize(new java.awt.Dimension(600, 480));
        // defPane.setSize(new Dimension(600, 480));

        setFrame = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        ComBox = new javax.swing.JComboBox();
        BaudBox = new javax.swing.JComboBox();
        DataBox = new javax.swing.JComboBox();
        StopBox = new javax.swing.JComboBox();
        ParityBox = new javax.swing.JComboBox();
        FlowBox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        setButton = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        closeset = new javax.swing.JButton();
        aboutFrame = new javax.swing.JInternalFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        sfield = new javax.swing.JTextField();
        sendbutton = new javax.swing.JButton();
        testf = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        openp = new javax.swing.JButton();
        closep = new javax.swing.JButton();
        recBufft = new javax.swing.JTabbedPane();
        jScrollPane5 = new javax.swing.JScrollPane();
        asciiBuff = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        recBuff = new javax.swing.JTextArea();
        jScrollPane4 = new javax.swing.JScrollPane();
        decBuff = new javax.swing.JTextArea();
        jScrollPane6 = new javax.swing.JScrollPane();
        binBuff = new javax.swing.JTextArea();
        jMenuBar3 = new javax.swing.JMenuBar();
        filemenu = new javax.swing.JMenu();
        newPrj = new javax.swing.JMenuItem();
        Save = new javax.swing.JMenuItem();
        loadPrj = new javax.swing.JMenuItem();
        exitMenu = new javax.swing.JMenuItem();
        Buffer = new javax.swing.JMenu();
        Clearbuff = new javax.swing.JMenuItem();
        setmenu = new javax.swing.JMenu();
        comset = new javax.swing.JMenuItem();
        optMenu = new javax.swing.JMenuItem();
        helpmenu = new javax.swing.JMenu();
        aboutmenu = new javax.swing.JMenuItem();

        defPane.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        defPane.setTitle("串口設置");
        defPane.setLocation(750, 100);

        // full Screen
        // defPane.setMaximizedBounds(defPane.getMaximizedBounds());
        // defPane.setExtendedState(MAXIMIZED_BOTH);

        setFrame.getContentPane().setLayout(
                new java.awt.GridLayout(3, 6, 7, 10));

        setFrame.setClosable(true);
        setFrame.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setFrame.setPreferredSize(new java.awt.Dimension(300, 130));

        jLabel1.setText("串口端口");// com port
        setFrame.getContentPane().add(jLabel1);

        jLabel2.setText("波特率");// Baud Rate
        setFrame.getContentPane().add(jLabel2);

        jLabel3.setText("數(shù)據(jù)位");// Bits
        setFrame.getContentPane().add(jLabel3);

        jLabel4.setText("停止位");// Stop Bits
        setFrame.getContentPane().add(jLabel4);

        jLabel5.setText("奇偶校驗");// Parity
        setFrame.getContentPane().add(jLabel5);

        jLabel6.setText("流控制");// Flow Control
        setFrame.getContentPane().add(jLabel6);

        ComBox.setModel(new javax.swing.DefaultComboBoxModel(
                new String[] { "COM1" }));
        setFrame.getContentPane().add(ComBox);

        BaudBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "38400", "300", "600", "1200", "2400", "4800", "9600", "19200",
                "57600", "115200" }));
        setFrame.getContentPane().add(BaudBox);

        DataBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "8", "7", "6" }));
        setFrame.getContentPane().add(DataBox);

        StopBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "1", "2" }));// STOPBITS_2,STOPBITS_1
        setFrame.getContentPane().add(StopBox);

        ParityBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "無", "奇", "偶" }));// PARITY_NONE,PARITY_ODD,PARITY_EVEN
        setFrame.getContentPane().add(ParityBox);

        FlowBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "無", "RTSCTS_IN模式", "RTSCTS_OUT模式", "XONXOFF_IN模式",
                "XONXOFF_OUT模式" }));
        // FlowBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
        // "FLOWCONTROL_NONE", "FLOWCONTROL_RTSCTS_IN",
        // "FLOWCONTROL_RTSCTS_OUT", "FLOWCONTROL_XONXOFF_IN",
        // "FLOWCONTROL_XONXOFF_OUT" }));
        setFrame.getContentPane().add(FlowBox);

        setFrame.getContentPane().add(jLabel7);

        setButton.setText("確定");// OK
        setButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setButtonActionPerformed(evt);
            }
        });

        setFrame.getContentPane().add(setButton);

        setFrame.getContentPane().add(jLabel9);

        setFrame.getContentPane().add(jLabel8);

        closeset.setText("取消");// 取消
        closeset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closesetActionPerformed(evt);
            }
        });

        setFrame.getContentPane().add(closeset);

        defPane.getContentPane().add(setFrame, java.awt.BorderLayout.NORTH);

        aboutFrame.setClosable(true);
        aboutFrame
                .setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        aboutFrame.setMinimumSize(new java.awt.Dimension(95, 39));
        aboutFrame.setPreferredSize(new java.awt.Dimension(600, 300));
        try {
            aboutFrame.setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1
                .setText("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\t\t\t                RS232TM 0.2 Alpha by Kotkis\n\n \t\t\t       This program can be freely distributed under GPL \n\n\t\t\t       For help ,support , bug report and everything else \n\n\t\t\t              http://www.sourceforge.net/rsmon\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n JRE 1.5 or later is needed to run this program - http://sun.java.com\n Also javacomm20-win32  is needed - \n\nhttp://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=7235-javacomm-2.0-spec-oth-JSpec&SiteId=JSC&TransactionId=noreg\n\nhttp://www.freepoc.org/download/javacomm20-win32.zip");
        jScrollPane1.setViewportView(jTextArea1);

        aboutFrame.getContentPane().add(jScrollPane1,
                java.awt.BorderLayout.CENTER);

        defPane.getContentPane().add(aboutFrame, java.awt.BorderLayout.CENTER);
        aboutFrame.getAccessibleContext().setAccessibleName("關于框架");// aboutFrame

        jScrollPane2.setAutoscrolls(true);
        jScrollPane2.setMinimumSize(new java.awt.Dimension(200, 23));
        jScrollPane2.setPreferredSize(new java.awt.Dimension(200, 100));
        jPanel2.setLayout(new java.awt.GridLayout(200, 2, 1, 1));

        jPanel2.setMinimumSize(new java.awt.Dimension(150, 479));
        jPanel2.setOpaque(false);
        jPanel2.setPreferredSize(new java.awt.Dimension(180, 5000));
        sfield.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sfield1ActionPerformed(evt);
            }
        });
        sfield.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                sfieldKeyReleased(evt);
            }
        });

        jPanel2.add(sfield);

        sendbutton.setText("發(fā)送");
        sendbutton.setToolTipText("此時只有1個字節(jié)可以被發(fā)送\n");// At this time only 1 byte
                                                        // can be send
        sendbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendbuttonActionPerformed(evt);
            }
        });

        jPanel2.add(sendbutton);

        testf.setEditable(false);
        jPanel2.add(testf);

        jScrollPane2.setViewportView(jPanel2);

        defPane.getContentPane().add(jScrollPane2, java.awt.BorderLayout.WEST);

        openp.setText("打開端口");// Open Port
        openp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openpActionPerformed(evt);
            }
        });

        jPanel1.add(openp);

        closep.setText("關閉端口");// Close port
        closep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closepActionPerformed(evt);
            }
        });

        jPanel1.add(closep);

        defPane.getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        recBufft.setAutoscrolls(true);
        jScrollPane5
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane5.setAutoscrolls(true);
        jScrollPane5
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane5ComponentShown(evt);
                    }
                });

        asciiBuff.setColumns(20);
        asciiBuff.setEditable(false);
        asciiBuff.setRows(5);
        jScrollPane5.setViewportView(asciiBuff);

        recBufft.addTab("ASCII", jScrollPane5);

        jScrollPane3
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane3.setAutoscrolls(true);
        jScrollPane3
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane3ComponentShown(evt);
                    }
                });

        recBuff.setColumns(20);
        recBuff.setEditable(false);
        recBuff.setRows(5);
        recBuff.setAutoscrolls(false);
        recBuff.setFocusCycleRoot(true);
        jScrollPane3.setViewportView(recBuff);

        recBufft.addTab("十六進制", jScrollPane3);// HEX

        jScrollPane4
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane4.setAutoscrolls(true);
        jScrollPane4
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane4ComponentShown(evt);
                    }
                });

        decBuff.setColumns(20);
        decBuff.setEditable(false);
        decBuff.setRows(5);
        decBuff.setAutoscrolls(false);
        decBuff.setFocusCycleRoot(true);
        jScrollPane4.setViewportView(decBuff);

        recBufft.addTab("十進制", jScrollPane4);// DEC

        jScrollPane6
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane6.setAutoscrolls(true);
        jScrollPane6
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane6ComponentShown(evt);
                    }
                });

        binBuff.setColumns(20);
        binBuff.setEditable(false);
        binBuff.setRows(5);
        binBuff.setAutoscrolls(false);
        binBuff.setFocusCycleRoot(true);
        jScrollPane6.setViewportView(binBuff);

        recBufft.addTab("二進制", jScrollPane6);// BIN

        recBufft.setSelectedIndex(1);

        defPane.getContentPane().add(recBufft, java.awt.BorderLayout.CENTER);

        filemenu.setText("工程");
        newPrj.setText("新建");
        newPrj.setEnabled(false);
        filemenu.add(newPrj);

        Save.setText("保存");
        Save.setEnabled(false);
        filemenu.add(Save);

        loadPrj.setText("裝載");
        loadPrj.setEnabled(false);
        filemenu.add(loadPrj);

        exitMenu.setText("退出");
        exitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuActionPerformed(evt);
            }
        });

        filemenu.add(exitMenu);

        jMenuBar3.add(filemenu);

        Buffer.setText("緩存");
        Clearbuff.setText("清除緩存 ");
        Clearbuff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearbuffActionPerformed(evt);
            }
        });

        Buffer.add(Clearbuff);

        jMenuBar3.add(Buffer);

        setmenu.setText("設置");
        comset.setText("串口設置");
        comset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comsetActionPerformed(evt);
            }
        });

        setmenu.add(comset);

        optMenu.setText("選項");
        optMenu.setEnabled(false);
        setmenu.add(optMenu);

        jMenuBar3.add(setmenu);

        helpmenu.setText("幫助");
        aboutmenu.setText("關于");
        aboutmenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutmenuActionPerformed(evt);
            }
        });

        helpmenu.add(aboutmenu);

        jMenuBar3.add(helpmenu);

        defPane.setJMenuBar(jMenuBar3);

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setEnabled(false);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 0, 0));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
                .getScreenSize();
        setBounds((screenSize.width - 365) / 2, (screenSize.height - 240) / 2,
                365, 240);
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_exitMenuActionPerformed
        System.exit(0); // Menu Exit Code - save Project ?

    }// GEN-LAST:event_exitMenuActionPerformed

    private void sfieldKeyReleased(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_sfieldKeyReleased
        // TODO add your handling code here:
        String s = sfield.getText();
        if (s.length() > 0) {
            if (radix != 0) {
                try {
                    int v = Integer.parseInt(sfield.getText(), radix);
                } // Routine for removing invalid simbols
                catch (Exception e) {
                    int a = s.length(); // in ascii mode everithing is valid
                    sfield.setText(s.substring(0, a - 1)); // remove invalid
                                                            // char
                }
            }
        }
    }// GEN-LAST:event_sfieldKeyReleased

    private void jScrollPane6ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane6ComponentShown
        // TODO add your handling code here:
        testf.setText("二進制模式"); // converting between modes
        int oldRadix = radix;
        radix = 2;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane6ComponentShown

    private void jScrollPane4ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane4ComponentShown
        // TODO add your handling code here:
        testf.setText("十進制模式");
        int oldRadix = radix;
        radix = 10;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane4ComponentShown

    private void jScrollPane3ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane3ComponentShown
        // TODO add your handling code here:
        testf.setText("十六進制模式");
        int oldRadix = radix;
        radix = 16;
        String s = null;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane3ComponentShown

    private void jScrollPane5ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane5ComponentShown
        // TODO add your handling code here:
        testf.setText("ASCII碼模式");
        int oldRadix = radix;
        radix = 0;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane5ComponentShown

    private void formWindowActivated(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowActivated
        setVisible(false);
        defPane.setVisible(true);

    }// GEN-LAST:event_formWindowActivated

    private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_setButtonActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(false);
        try {
            serialPort.close();
            txt = ("串口 " + serialPort.getName() + " 關閉\n");
            buffWrite(txt);
        } catch (Exception e) {
            txt = ("串口未能關閉\n");
            buffWrite(txt);
        }
        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(
                            (String) ComBox.getSelectedItem())) { // For Windows
                                                                    // settings
                        // if (portId.getName().equals("/dev/term/a")) { //For
                        // Linux settings
                        SimpleRead();
                    }
                }
            }
        } catch (Exception e) {
            txt = ("串口關閉\n");
            buffWrite(txt);
            ;
        }

    }// GEN-LAST:event_setButtonActionPerformed

    private void closesetActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_closesetActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(false);
    }// GEN-LAST:event_closesetActionPerformed

    private void openpActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_openp1ActionPerformed
        // TODO add your handling code here:

        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(
                            (String) ComBox.getSelectedItem())) { // For Windows
                                                                    // settings
                        // if (portId.getName().equals("/dev/term/a")) { //For
                        // Linux settings
                        SimpleRead();
                    }
                }
            }
        } catch (Exception e) {
            txt = ("串口關閉\n");
            buffWrite(txt);
            ;
        }
    }// GEN-LAST:event_openp1ActionPerformed

    private void comsetActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_comsetActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(true);
        ComBox.removeAllItems();
        // ComBox.addItem("COM1");
        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    ComBox.addItem(portId.getName()); // For Windows
                    System.out.println("當前檢測到的串口: " + portId.getName());
                    // settings
                    // if (portId.getName().equals("/dev/term/a")) { //For Linux
                    // settings

                }
            }
        } catch (Exception e) {
            txt = ("無法獲得端口\n");
            buffWrite(txt);
        }

    }// GEN-LAST:event_comsetActionPerformed

    private void ClearbuffActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_ClearbuffActionPerformed
        // TODO add your handling code here:
        recBuff.setText("");
        asciiBuff.setText("");
        decBuff.setText("");
        binBuff.setText("");

    }// GEN-LAST:event_ClearbuffActionPerformed

    private void sendbuttonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_sendbuttonActionPerformed
        // TODO add your handling code here:
        senddata();

    }// GEN-LAST:event_sendbuttonActionPerformed

    private void aboutmenuActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_aboutmenuActionPerformed
        // TODO add your handling code here:
        aboutFrame.setVisible(true);
        try {
            aboutFrame.setMaximum(true);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_aboutmenuActionPerformed

    private void sfield1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_sfieldActionPerformed
        // TODO add your handling code here:
        senddata();

    }// GEN-LAST:event_sfieldActionPerformed

    private void senddata() {
        String s = null;
        s = sfield.getText();
        SerialWrite(s);

        // recBuff.append(">>"+s+"\n"); //TODO add ascii view
        // txt=(">>"+s+"\n");
        // buffWrite(txt);
    }

    private void closepActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_closepActionPerformed
        // TODO add your handling code here:
        try {
            serialPort.close();
            txt = ("串口 " + serialPort.getName() + " 關閉 \n");
            buffWrite(txt);
        } catch (Exception e) {
            txt = ("串口關閉\n");
            buffWrite(txt);
        }
    }// GEN-LAST:event_closepActionPerformed

    /*
     * public static void main(String args[]) {
     * java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new
     * INT1().setVisible(true); } }); }
     */

    public void serialEvent(SerialPortEvent event) {// 串口數(shù)據(jù)處理函數(shù)
        switch (event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            int w;
            try {
                txt = ("<<");
                buffWrite(txt);
                // function 內(nèi)部計數(shù)變量,每一幀數(shù)據(jù)個數(shù)為100
                int count = 0;

                while (inputStream.available() > 0) {

                    w = inputStream.read();
                    recBuff.append(Integer.toString(w, 16) + " "); // TODO radix
                                                                    // replacement
                    decBuff.append(Integer.toString(w, 10) + " ");
                    binBuff.append(Integer.toString(w, 2) + " ");
                    String aChar = new Character((char) w).toString();
                    asciiBuff.append("" + aChar); // ASCII output
                    
                    // 將每一幀的數(shù)據(jù)保存到output
                    output += Integer.toString(w, 16) + " ";
                    count++;
                    if (count % 100 == 0 && count > 0) {
                        outputData.add(output);
                        //System.out.print(outputData.get(groupNums));
                        
                        //wirte data to client
                        outputToClient.writeObject(outputData.get(groupNums));
                        groupNums++;
                        //clear output
                        output = "";
                        
                        //System.out.println("counts: " + count);
                        //count = 0;
                    }
                }
                txt = ("\n");
                buffWrite(txt);
            } catch (IOException e) {
            }
            break;
        }
    }

    public void SimpleRead() {// 簡單讀取程序
        Boolean open = true;
        try {
            if (portId.isCurrentlyOwned() == false) {
                serialPort = (SerialPort) portId.open("RS232TM", 2000);

                txt = ("串口 " + serialPort.getName() + "打開\n");
                buffWrite(txt);
            } else {
                txt = ("串口 " + serialPort.getName() + " 已經(jīng)被 "
                        + portId.getCurrentOwner() + "打開 \n");
                buffWrite(txt);
                open = false;
            }
        } catch (PortInUseException e) {
            txt = ("串口打開\n");
            open = false;
            buffWrite(txt);
        }
        if (open == true) {
            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            serialPort.notifyOnDataAvailable(true);

            try {

                int f = Integer.parseInt((String) BaudBox.getSelectedItem());
                serialPort.setSerialPortParams(f,
                        8 - DataBox.getSelectedIndex(),
                        StopBox.getSelectedIndex() + 1,
                        ParityBox.getSelectedIndex());
                f = FlowBox.getSelectedIndex();
                if (f == 4)
                    f = 8;
                if (f == 3)
                    f = 4;
                serialPort.setFlowControlMode(f);
                String txt = ("參數(shù): " + serialPort.getBaudRate() + "比特/秒 , "
                        + serialPort.getDataBits() + "位 , "
                        + serialPort.getStopBits() + "停止位 , 奇偶校驗 模式: "
                        + serialPort.getParity() + " , 流控制模式:"
                        + serialPort.getFlowControlMode() + " \n");
                buffWrite(txt);
            } catch (UnsupportedCommOperationException e) {
                txt = ("不支持的通信 參數(shù)\n");
                buffWrite(txt);
            }

        }
    }

    public void SerialWrite(String s) {// 簡單寫入程序
        try {
            try {
                outputStream = serialPort.getOutputStream();
            } catch (IOException e) {
                txt = ("串口錯誤11\n");
                buffWrite(txt);
            }
            int val = 0;
            char c;

            if (radix == 0) {
                c = s.charAt(0);
                val = c;
                outputStream.write(val);
            }

            else {
                val = Integer.parseInt(s, radix);
                outputStream.write(val);
                c = new Character((char) val);// .toString();
            }

            asciiBuff.append(">>" + c + "\n");
            recBuff.append(">>" + Integer.toString(val, 16) + "\n "); // TODO
                                                                        // radix
                                                                        // replacement
            decBuff.append(">>" + Integer.toString(val, 10) + "\n ");
            binBuff.append(">>" + Integer.toString(val, 2) + "\n ");

        } catch (IOException e) {
            txt = ("串口錯誤 12\n");
            buffWrite(txt);
        }
    }

    public void buffWrite(String s) {
        recBuff.append(s);
        asciiBuff.append(s);
        decBuff.append(s);
        binBuff.append(s);
        recBuff.setCaretPosition(recBuff.getDocument().getLength());
        asciiBuff.setCaretPosition(asciiBuff.getDocument().getLength());
        decBuff.setCaretPosition(decBuff.getDocument().getLength());
        binBuff.setCaretPosition(binBuff.getDocument().getLength());
    }

    public void updateSfield(String s1, int oldRadix) {
        int v;
        if (oldRadix != 0) {
            v = Integer.parseInt(s1, oldRadix);
            if (radix == 0) {
                String aChar = new Character((char) v).toString();
                sfield.setText(aChar);
            }

            else {
                sfield.setText(Integer.toString(v, radix));
            }
        } else {
            char c = s1.charAt(0);
            v = c;
            sfield.setText(Integer.toString(v, radix));
            // sfield.setText(""+Integer.parseInt( s1, radix ));
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox BaudBox;
    private javax.swing.JMenu Buffer;
    private javax.swing.JMenuItem Clearbuff;
    private javax.swing.JComboBox ComBox;
    private javax.swing.JComboBox DataBox;
    private javax.swing.JComboBox FlowBox;
    private javax.swing.JComboBox ParityBox;
    private javax.swing.JMenuItem Save;
    private javax.swing.JComboBox StopBox;
    private javax.swing.JInternalFrame aboutFrame;
    private javax.swing.JMenuItem aboutmenu;
    private javax.swing.JTextArea asciiBuff;
    private javax.swing.JTextArea binBuff;
    private javax.swing.JButton closep;
    private javax.swing.JButton closeset;
    private javax.swing.JMenuItem comset;
    private javax.swing.JTextArea decBuff;
    private javax.swing.JFrame defPane;
    private javax.swing.JMenuItem exitMenu;
    private javax.swing.JMenu filemenu;
    private javax.swing.JMenu helpmenu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenuBar jMenuBar3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JMenuItem loadPrj;
    private javax.swing.JMenuItem newPrj;
    private javax.swing.JButton openp;
    private javax.swing.JMenuItem optMenu;
    private javax.swing.JTextArea recBuff;
    private javax.swing.JTabbedPane recBufft;
    private javax.swing.JButton sendbutton;
    private javax.swing.JButton setButton;
    private javax.swing.JInternalFrame setFrame;
    private javax.swing.JMenu setmenu;
    private javax.swing.JTextField sfield;
    private javax.swing.JTextField testf;

    // End of variables declaration//GEN-END:variables

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new INT1().setVisible(true);
            }
        });
    }

}

代碼的注釋應該是比較清楚的亲桥,我自己加入了數(shù)據(jù)存儲并把這個作為服務端發(fā)送數(shù)據(jù)洛心,僅供參考哦~

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市题篷,隨后出現(xiàn)的幾起案子词身,更是在濱河造成了極大的恐慌,老刑警劉巖番枚,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件法严,死亡現(xiàn)場離奇詭異,居然都是意外死亡葫笼,警方通過查閱死者的電腦和手機深啤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來路星,“玉大人溯街,你說我怎么就攤上這事⊙筘ぃ” “怎么了呈昔?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長友绝。 經(jīng)常有香客問我韩肝,道長,這世上最難降的妖魔是什么九榔? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任哀峻,我火速辦了婚禮,結果婚禮上哲泊,老公的妹妹穿的比我還像新娘剩蟀。我一直安慰自己,他們只是感情好切威,可當我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布育特。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪缰冤。 梳的紋絲不亂的頭發(fā)上犬缨,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天,我揣著相機與錄音棉浸,去河邊找鬼怀薛。 笑死,一個胖子當著我的面吹牛迷郑,可吹牛的內(nèi)容都是我干的枝恋。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼嗡害,長吁一口氣:“原來是場噩夢啊……” “哼焚碌!你這毒婦竟也來了?” 一聲冷哼從身側響起霸妹,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤十电,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叹螟,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鹃骂,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年首妖,在試婚紗的時候發(fā)現(xiàn)自己被綠了偎漫。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡有缆,死狀恐怖象踊,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情棚壁,我是刑警寧澤杯矩,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站袖外,受9級特大地震影響史隆,放射性物質發(fā)生泄漏。R本人自食惡果不足惜曼验,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一泌射、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鬓照,春花似錦熔酷、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春躺酒,著一層夾襖步出監(jiān)牢的瞬間押蚤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工羹应, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留揽碘,地道東北人。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓量愧,卻偏偏與公主長得像钾菊,于是被迫代替她去往敵國和親帅矗。 傳聞我的和親對象是個殘疾皇子偎肃,可洞房花燭夜當晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容