---
title: "java  条码仪"
author: "hwpok"
date: "2009-10-28T16:28:00Z"
tags: []
slug: "java"
draft: false
lastmod: "2009-10-28T16:28:00Z"
id: 615726
url: "https://hwpok.iteye.com/blog/615726"
---

这个是一个JAVA代码的解决方案，但我测试后发现读不到数据，不知道那里有问题，现在还没有解决。

package com;    

/*      
程序文件名称：ReadComm.java      
功能：从串行口COM1中接收数据      
\*/      
import java.awt.\*;      
import java.awt.event.\*;      
import java.io.\*;      
import java.util.\*;      
import javax.comm.\*;    

class R\_Frame extends Frame implements Runnable,ActionListener,SerialPortEventListener      
    {      
/* 检测系统中可用的通讯端口类 \*/      
    static CommPortIdentifier portId;      
/* Enumeration 为枚举型类,在java.util中 \*/      
    static Enumeration portList;      
    InputStream inputStream;      
/* 声明RS-232串行端口的成员变量 \*/      
    SerialPort serialPort;      
    Thread readThread;      
    String str="";      
    TextField out\_message=new TextField("上面文本框显示接收到的数据");      
    TextArea in\_message=new TextArea();      
    Button btnOpen=new Button("打开串口");      
/\*建立窗体\*/      
    R\_Frame()      
    {      
    super("串口接收数据");      
    setSize(200,200);      
    setVisible(true);      
    btnOpen.addActionListener(this);      
    add(out\_message,"South");      
    add(in\_message,"Center");      
    add(btnOpen,"North");      
      
          
          
    /\*获取系统中所有的通讯端口 \*/      
        portList=CommPortIdentifier.getPortIdentifiers();      
            /* 用循环结构找出串口 \*/      
        while (portList.hasMoreElements()){      
        /\*强制转换为通讯端口类型\*/      
        portId=(CommPortIdentifier)portList.nextElement();      
        if(portId.getPortType() == CommPortIdentifier.PORT\_SERIAL){      
            if (portId.getName().equals("COM1")) {      
                try {      
            serialPort = (SerialPort) portId.open("ReadComm", 2000);      
            out\_message.setText("已打开端口COM1 ,正在接收数据..... ");      
            }      
        catch (PortInUseException e) { }    

        /\*设置串口监听器\*/      
        try {      
        serialPort.addEventListener(this);      
        }      
        catch (TooManyListenersException e) { }      
        /* 侦听到串口有数据,触发串口事件\*/      
        serialPort.notifyOnDataAvailable(true);      
        } //if end      
        } //if end      
        } //while end      
        readThread = new Thread(this);      
        readThread.start(); //线程负责每接收一次数据休眠20秒钟      
        } //R\_Frame() end    

      
    /\*点击按扭所触发的事件：打开串口,并监听串口. \*/      
public void actionPerformed(ActionEvent event)      
    {      
        /\*获取系统中所有的通讯端口 \*/      
        portList=CommPortIdentifier.getPortIdentifiers();      
        /* 用循环结构找出串口 \*/      
        while (portList.hasMoreElements()){      
        /\*强制转换为通讯端口类型\*/      
        portId=(CommPortIdentifier)portList.nextElement();      
        if(portId.getPortType() == CommPortIdentifier.PORT\_SERIAL){      
        if (portId.getName().equals("COM1")) {      
        try {      
        serialPort = (SerialPort) portId.open("ReadComm", 2000);      
        out\_message.setText("已打开端口COM1 ,正在接收数据..... ");      
        }      
        catch (PortInUseException e) { }    

    /\*设置串口监听器\*/      
        try {      
        serialPort.addEventListener(this);      
        }      
        catch (TooManyListenersException e) { }      
    /* 侦听到串口有数据,触发串口事件\*/      
        serialPort.notifyOnDataAvailable(true);      
        } //if end      
        } //if end      
        } //while end      
        readThread = new Thread(this);      
        readThread.start(); //线程负责每接收一次数据休眠20秒钟      
        } //actionPerformed() end    

        /\*接收数据后休眠20秒钟\*/      
public void run() {      
        try {      
        Thread.sleep(20000);      
        }      
    catch (InterruptedException e) { }      
        } //run() end    

        /\*串口监听器触发的事件，设置串口通讯参数，读取数据并写到文本区中\*/      
public void serialEvent(SerialPortEvent event) {      
    /\*设置串口通讯参数：波特率、数据位、停止位、奇偶校验\*/      
        try {      
        serialPort.setSerialPortParams(9600,      
        SerialPort.DATABITS\_8,      
        SerialPort.STOPBITS\_1,      
        SerialPort.PARITY\_NONE);      
        }      
        catch (UnsupportedCommOperationException e) {}      
            byte\[] readBuffer = new byte\[20];      
        try {      
            inputStream = serialPort.getInputStream();      
        }      
        catch (IOException e){      
}      
        try {    

        while (inputStream.available() &gt; 0)      
        {      
            int numBytes = inputStream.read(readBuffer);      
                } //while end      
            str=new String(readBuffer);      
        /\*接收到的数据存放到文本区中\*/      
            in\_message.append(str+"\\n");      
            }      
            catch (IOException e){      
            }      
            } //serialEvent() end      
        } //类R\_Frame end    

        public class ReadComm      
        {      
public static void main(String args\[])      
        {      
        /* 实例化接收串口数据的窗体类 \*/      
        R\_Frame R\_win=new R\_Frame();      
        /* 定义窗体适配器的关闭按钮功能 \*/      
        R\_win.addWindowListener(new WindowAdapter()      
        {      
        public void windowClosing(WindowEvent e)      
        {      
        System.exit(0);      
        }      
    });      
        R\_win.pack();      
    }      
}    

 

 

 

这个是在web页面上的实现，修改了下现在可以读到数据，但这个需要注册MSCOMM组件，还算比较理想吧！

&lt;%@ page contentType="text/html; charset=gb2312" language="java"    %&gt;      
&lt;html&gt;      
&lt;head&gt;      
&lt;title&gt;JavaScript MSCOMM32.OCX &lt;/title&gt;    

&lt;SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript&gt;      
//重写 mscomm 控件的唯一事件处理代码      
function MSComm1\_OnComm()      
{      
var len=0;      
if(MSComm1.CommEvent==1)//如果是发送事件      
{      
    window.alert("请读条码");//这句正常，说明发送成功了      
}      
else if(MSComm1.CommEvent==2)//如果是接收事件      
{      
        document.form1.txtReceive.value=document.form1.txtReceive.value + MSComm1.Input;      
}    

}      
&lt;/SCRIPT&gt;    

&lt;SCRIPT LANGUAGE=javascript FOR=MSComm1 EVENT=OnComm&gt;      
// MSComm1控件每遇到 OnComm 事件就调用 MSComm1\_OnComm()函数      
MSComm1\_OnComm()      
&lt;/SCRIPT&gt;    

&lt;script language="JavaScript" type="text/JavaScript"&gt;      
//打开端口并发送命令程序      
function OpenPort()      
{      
if(MSComm1.PortOpen==false)      
{      
MSComm1.PortOpen=true;      
MSComm1.Output="R";//发送命令      
//window.alert("成功发出命令！");  
}      
else      
{      
    window.alert ("已经开始接收数据!");      
}      
}      
&lt;/script&gt;    

&lt;/head&gt;      
&lt;OBJECT CLASSID="clsid:648A5600-2C6E-101B-82B6-000000000014" id=MSComm1 codebase="MSCOMM32.OCX" type="application/x-oleobject"      
style="LEFT: 54px; TOP: 14px" &gt;      
&lt;PARAM NAME="CommPort" VALUE="1"&gt;      
&lt;PARAM NAME="DTREnable" VALUE="1"&gt;      
&lt;PARAM NAME="Handshaking" VALUE="0"&gt;      
&lt;PARAM NAME="InBufferSize" VALUE="1024"&gt;      
&lt;PARAM NAME="InputLen" VALUE="0"&gt;      
&lt;PARAM NAME="NullDiscard" VALUE="0"&gt;      
&lt;PARAM NAME="OutBufferSize" VALUE="512"&gt;      
&lt;PARAM NAME="ParityReplace" VALUE="?"&gt;      
&lt;PARAM NAME="RThreshold" VALUE="1"&gt;      
&lt;PARAM NAME="RTSEnable" VALUE="1"&gt;      
&lt;PARAM NAME="SThreshold" VALUE="2"&gt;      
&lt;PARAM NAME="EOFEnable" VALUE="0"&gt;      
&lt;PARAM NAME="InputMode" VALUE="0"&gt;    

&lt;PARAM NAME="DataBits" VALUE="8"&gt;      
&lt;PARAM NAME="StopBits" VALUE="1"&gt;      
&lt;PARAM NAME="BaudRate" VALUE="9600"&gt;      
&lt;PARAM NAME="Settings" VALUE="9600,N,8,1"&gt;      
&lt;/OBJECT&gt;    

&lt;body&gt;      
&lt;form name="form1"&gt;      
&lt;input type="button" name="Submit" value="提交" onClick="OpenPort()"&gt;      
&lt;input type="text" name="txtReceive" size=50 value=""&gt;      
&lt;/form&gt;      
&lt;/body&gt;      
&lt;/html&gt;