} public void serialEvent(SerialPortEvent event)//实现串口监听中的方法 { 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: //串口有数据 byte[] readBuffer=new byte[1]; try { while(inputStream.available()>-1) { int numBytes=inputStream.read(readBuffer);//从输入流每次读取一个字节的数据 area.append(new String(readBuffer));//将下一个数据追加到尾部 //button1.setEnabled(false); //button2.setEnabled(false); } // button1.setEnabled(true); // button2.setEnabled(true); } catch(Exception e){ } break; } } }
javax.comm里 是有对java的一些操作,如读写串口等,不过没找到对串口输入缓冲区的操作.
公司现在再做一个短信项目,用的硬件是wevacome.网上的一段代码:
// 如果有串口事件发生
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try {
in = new DataInputStream(sPort.getInputStream());
sb = new StringBuffer();
while ((c = in.read()) != -1) {
sb.append((char) c); }运行后会出现这样一个问题: 取到的InputStream里的数据也会包含上次到达的数据.
推测应该是串口输入缓冲区的问题.
所有想找一个清楚串口输入缓冲区方法.
代码也是来字网上:http://www.javatx.cn/clubPage.jsp?ccStyle=0&tID=1004&ccID=26
import java.io.*;
import java.util.*;
import javax.comm.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author tian
*/
public class ComTest {
/** Creates a new instance of ComTest */
public ComTest() {
com c=new com();
c.setTitle("串口测试");
c.setSize(400,400);
c.setResizable(false);
c.setVisible(true);
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
c.setLocation((screen.width-400)/2,(screen.height-400)/2);
}
public static void main(String[]args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception exception) {
exception.printStackTrace();
}
new ComTest();
}
});
}
}
class com extends JFrame implements ActionListener,SerialPortEventListener{
static Enumeration portList;//枚举类型
static CommPortIdentifier portId;/* 检测系统中可用的通讯端口类 */
static SerialPort serialPort;/* 声明RS-232串行端口的成员变量 */
static OutputStream outputStream;//输出流
static InputStream inputStream;//输入流
static boolean use=false;
static boolean flag=true;
JPanel panel;
JScrollPane scrollPane;
JTextField text=new JTextField();
JButton button1=new JButton("发送");
JButton button2=new JButton("自动发送");
JButton button3=new JButton("清除");
JTextArea area=new JTextArea();
JLabel label=new JLabel("手动发送");
String message;
com(){
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInt();
}
public void jbInt(){
panel=(JPanel)getContentPane();
panel.setLayout(null);
scrollPane=new JScrollPane(area);
label.setBounds(35,30,100,25);
text.setBounds(120,30,150,25);
button1.setBounds(290,30,80,23);
button2.setBounds(160,335,80,25);
button3.setBounds(280,335,80,25);
scrollPane.setBounds(35,70,340,250);
area.setFont(new Font("",Font.PLAIN,14));//设置字体大小
panel.add(label);
panel.add(text);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(scrollPane);
button1.addActionListener(this);//添加监听
button2.addActionListener(this);
button3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button1)
{
message=text.getText();//将text中的文本赋予message
if(message.length()>0)//判断message是否为空
{
System.out.println(message);
a(); //调用方法放
}
else
JOptionPane.showMessageDialog(null,"请输入数据"); //消息框
}
if(e.getSource()==button2){//判断是否button2
double d=Math.random();//产生随机数
String s=String.valueOf(d);//返回参数的字符串 表示形式
message=s.substring(2);//从指定索引处 返回一个新的字符串
System.out.println(message);
a(); //调用方法
}
if(e.getSource()==button3)
area.setText(null);
}
public void a(){
boolean portFound=false;
String defaultPort="COM1";
portList=CommPortIdentifier.getPortIdentifiers();//获得所有通信端口
while(portList.hasMoreElements())// 测试此枚举是否包含更多的元素
{
portId=(CommPortIdentifier)portList.nextElement();//返回此枚举的下一个元素
if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)//判断是否串口
{
if(portId.getName().equals(defaultPort))//判断是否COM1
{
portFound=true;
if(!use)
{
try
{
serialPort=(SerialPort)portId.open("com",2000);//打开串口
//System.out.println("串口"+portId.getName()+"已经打开");
area.setText("串口"+portId.getName()+"已经打开\n");
}
catch(PortInUseException a){
JOptionPane.showMessageDialog(null,"端口正在使用");//消息框
return;
}
}
try
{
outputStream=serialPort.getOutputStream();//设置输出流
}
catch(IOException a){}
try
{
serialPort.setSerialPortParams(9600,//设置串口通信参数
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch(UnsupportedCommOperationException a){}
try
{
serialPort.notifyOnOutputEmpty(true);//串口输出缓冲区空闲
}
catch(Exception a){}
try
{
area.append("\n");
outputStream.write(message.getBytes());//将数据写入输出流
outputStream.flush();
area.append("输出流: "+message+"\n");
use=true;
}
catch(IOException a){}
}
}
}
if(!portFound)
{
JOptionPane.showMessageDialog(null,"没有发现该端口");//消息框
return;
}
try
{
inputStream=serialPort.getInputStream();//设置输入流
area.append("输入流: ");
}
catch(IOException a){}
try
{
serialPort.addEventListener(this);//添加串口监听
}
catch(TooManyListenersException a){}
serialPort.notifyOnDataAvailable(true);
}
public void serialEvent(SerialPortEvent event)//实现串口监听中的方法
{
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: //串口有数据
byte[] readBuffer=new byte[1];
try
{
while(inputStream.available()>-1)
{
int numBytes=inputStream.read(readBuffer);//从输入流每次读取一个字节的数据
area.append(new String(readBuffer));//将下一个数据追加到尾部
//button1.setEnabled(false);
//button2.setEnabled(false);
}
// button1.setEnabled(true);
// button2.setEnabled(true);
}
catch(Exception e){
}
break;
}
}
}