这是我的java串口通信的程序,,,程序发送数据给一段..但从另一段发送数据给程序时,就出现问题了,,我接收到了,,只能是8个字符,,也就是说,,只能读取8个字节..后面的就读不出来了.....请问是什么问题import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.border.*;
import javax.comm.*;
import java.io.*;public class Send extends JFrame implements SerialPortEventListener{
Dimension dim = null;
Container con = null;
static Enumeration portList = null;
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();


JLabel l1 = new JLabel("通讯口设置");
JButton b2 = new JButton("Connect");
JButton b3 = new JButton("");
JButton b4 = new JButton("close");
private JButton b5 = new JButton("发送");

CommPortIdentifier portId;
SerialPort serialPort; 

JComboBox c1 = new JComboBox();
JTextField f1 = new JTextField();

OutputStream outputStream = null;

InputStream inputStream; 
private JLabel l2 = new JLabel("得到数据:");
private JLabel l3 = new JLabel("");

Thread t1 = new Thread(new T1(b3));



public Send(){

this.setTitle("串口通信测试");
dim = Toolkit.getDefaultToolkit().getScreenSize();
con = this.getContentPane();
con.setLayout(null);

t1.start();


int h = (int)dim.getHeight()-35;
int w = (int)dim.getWidth();

p2.setBorder(new TitledBorder("发送信息"));
p2.setLayout(null);
p2.setBounds(0,70,800,65);




p1.setBorder(new TitledBorder("端口设置"));
p1.setLayout(null);

p1.setSize(800,60);

p3.setBounds(0,150,800,505);
p3.setBorder(new TitledBorder("结果显示"));
p3.setLayout(null);


l1.setBounds(10,20,90,30);

c1.setBounds(100,20,90,25);
b2.setBounds(200,20,90,25);
b3.setBounds(300,20,90,25);
b4.setBounds(600,20,90,25);

f1.setBounds(10,20,300,30);
b5.setBounds(350,20,90,25);
l2.setBounds(460,20,90,25);
l3.setBounds(550,20,200,85);

p2.add(f1);
p2.add(b5);
p2.add(l2);
p2.add(l3);
getPort();

p1.add(l1);
p1.add(c1);
p1.add(b2);
p1.add(b3);
p1.add(b4);

b3.setVisible(false);
b4.setVisible(false);


con.add(p1);
con.add(p2);
con.add(p3);




b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
b1_button(e);
}
});

b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
b4_button(e);
}
});
b5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
b5_button(e);
}
});;
this.setSize(810,700);
Dimension cc=this.getSize();
int a=(int)(dim.getWidth()-cc.width)/2;
int b=(int)(dim.getHeight()-cc.height)/2;




this.setResizable(false);
this.setLocation(a,b);
this.setVisible(true);
}

/* 读取数据从com1 or com2口 */
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){
System.out.println(e.toString());

try { while (inputStream.available() > 0) { 
int numBytes = inputStream.read(readBuffer); 

String str=new String(readBuffer); System.out.println(str);

catch (IOException e) {

System.out.println(e.toString());
 } 



}




public void getPort(){

portList = CommPortIdentifier.getPortIdentifiers(); 
CommPortIdentifier portId=null; while(portList.hasMoreElements()){

portId = (CommPortIdentifier)portList.nextElement();
 if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                   c1.addItem(portId.getName());
                   
                }

}



}

public void b4_button(ActionEvent e){

b3.setVisible(false);

b2.setEnabled(true);
b4.setVisible(false);


serialPort.close();



}

public void b5_button(ActionEvent e){

try
{ serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); 

}catch(Exception ee){

JOptionPane.showMessageDialog(this,"请先连接串口","提示",JOptionPane.INFORMATION_MESSAGE);

}

try{

outputStream = serialPort.getOutputStream(); 
inputStream = serialPort.getInputStream();

String str = f1.getText();


outputStream.write(str.getBytes());


}catch(Exception ee){
JOptionPane.showMessageDialog(this,"请先连接串口","提示",JOptionPane.INFORMATION_MESSAGE);
}
}

public void b1_button(ActionEvent e){

//打开指定串口
String PortName = c1.getSelectedItem().toString();
try{

portId = CommPortIdentifier.getPortIdentifier(PortName);
b3.setVisible(true);

b3.setText("连接成功");


b2.setEnabled(false);
b4.setVisible(true);


}catch(Exception ec){

JOptionPane.showMessageDialog(this,"sorry,程序找不到这个端口","提示",JOptionPane.INFORMATION_MESSAGE);
b3.setVisible(true);
b3.setText("连接失败");
b3.setBackground(Color.red);
}
try{
serialPort = (SerialPort) portId.open("ReadComm", 2000); 

}catch(Exception ee){
JOptionPane.showMessageDialog(this,"sorry,端口正在使用中,请检查....","提示",JOptionPane.INFORMATION_MESSAGE);
b3.setVisible(true);

b3.setText("连接失败");

b3.setBackground(Color.red);

}


try { 
serialPort.addEventListener(this); 

catch (TooManyListenersException ee) { 

System.out.println(ee.toString());



}  serialPort.notifyOnDataAvailable(true); 




}

public static void main(String args[]){


new Send();


}}

解决方案 »

  1.   

    为了让别人好看  你应该使用java code打出来
      

  2.   

    javacodeimport javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.comm.*;
    import java.io.*;public class Send extends JFrame implements SerialPortEventListener{

    Dimension dim = null;
    Container con = null;
    static Enumeration portList = null;
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    JLabel l1 = new JLabel("通讯口设置");
    JButton b2 = new JButton("Connect");
    JButton b3 = new JButton("");
    JButton b4 = new JButton("close");
    private JButton b5 = new JButton("发送"); CommPortIdentifier portId;
    SerialPort serialPort; JComboBox c1 = new JComboBox();
    JTextField f1 = new JTextField(); OutputStream outputStream = null; InputStream inputStream;
    private JLabel l2 = new JLabel("得到数据:");
    private JLabel l3 = new JLabel(""); Thread t1 = new Thread(new T1(b3)); public Send(){ this.setTitle("串口通信测试");
    dim = Toolkit.getDefaultToolkit().getScreenSize();
    con = this.getContentPane();
    con.setLayout(null);
    t1.start();
    int h = (int)dim.getHeight()-35;
    int w = (int)dim.getWidth(); p2.setBorder(new TitledBorder("发送信息"));
    p2.setLayout(null);
    p2.setBounds(0,70,800,65);
    p1.setBorder(new TitledBorder("端口设置"));
    p1.setLayout(null); p1.setSize(800,60); p3.setBounds(0,150,800,505);
    p3.setBorder(new TitledBorder("结果显示"));
    p3.setLayout(null);
    l1.setBounds(10,20,90,30); c1.setBounds(100,20,90,25);
    b2.setBounds(200,20,90,25);
    b3.setBounds(300,20,90,25);
    b4.setBounds(600,20,90,25); f1.setBounds(10,20,300,30);
    b5.setBounds(350,20,90,25);
    l2.setBounds(460,20,90,25);
    l3.setBounds(550,20,200,85); p2.add(f1);
    p2.add(b5);
    p2.add(l2);
    p2.add(l3);
    getPort(); p1.add(l1);
    p1.add(c1);
    p1.add(b2);
    p1.add(b3);
    p1.add(b4); b3.setVisible(false);
    b4.setVisible(false);
    con.add(p1);
    con.add(p2);
    con.add(p3);
    b2.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    b1_button(e);
    }
    }); b4.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    b4_button(e);
    }
    });
    b5.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    b5_button(e);
    }
    });;
    this.setSize(810,700);
    Dimension cc=this.getSize();
    int a=(int)(dim.getWidth()-cc.width)/2;
    int b=(int)(dim.getHeight()-cc.height)/2;
    this.setResizable(false);
    this.setLocation(a,b);
    this.setVisible(true);
    } /* 读取数据从com1 or com2口 */
    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){
    System.out.println(e.toString());
    }
    try { while (inputStream.available() > 0) {
    int numBytes = inputStream.read(readBuffer);
    }
    String str=new String(readBuffer);
    System.out.println(str);
    }
    catch (IOException e) { System.out.println(e.toString());
    }

    }
    public void getPort(){ portList = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId=null; while(portList.hasMoreElements()){ portId = (CommPortIdentifier)portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    c1.addItem(portId.getName());
                     
    } } } public void b4_button(ActionEvent e){ b3.setVisible(false); b2.setEnabled(true);
    b4.setVisible(false);
    serialPort.close(); } public void b5_button(ActionEvent e){ try
    { serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); }catch(Exception ee){ JOptionPane.showMessageDialog(this,"请先连接串口","提示",JOptionPane.INFORMATION_MESSAGE); } try{ outputStream = serialPort.getOutputStream();
    inputStream = serialPort.getInputStream(); String str = f1.getText();
    outputStream.write(str.getBytes());
    }catch(Exception ee){
    JOptionPane.showMessageDialog(this,"请先连接串口","提示",JOptionPane.INFORMATION_MESSAGE);
    }
    } public void b1_button(ActionEvent e){ //打开指定串口
    String PortName = c1.getSelectedItem().toString();
    try{ portId = CommPortIdentifier.getPortIdentifier(PortName);
    b3.setVisible(true); b3.setText("连接成功");
    b2.setEnabled(false);
    b4.setVisible(true);
    }catch(Exception ec){ JOptionPane.showMessageDialog(this,"sorry,程序找不到这个端口","提示",JOptionPane.INFORMATION_MESSAGE);
    b3.setVisible(true);
    b3.setText("连接失败");
    b3.setBackground(Color.red);
    }
    try{
    serialPort = (SerialPort) portId.open("ReadComm", 2000); }catch(Exception ee){
    JOptionPane.showMessageDialog(this,"sorry,端口正在使用中,请检查....","提示",JOptionPane.INFORMATION_MESSAGE);
    b3.setVisible(true); b3.setText("连接失败"); b3.setBackground(Color.red); }
    try {
    serialPort.addEventListener(this);
    }
    catch (TooManyListenersException ee) { System.out.println(ee.toString()); } serialPort.notifyOnDataAvailable(true);
    } public static void main(String args[]){
    new Send();
    }} 
      

  3.   

    serialEvent里面的响应代码会出问题,
    不是你的代码出问题,而是SerialPortEvent.DATA_AVAILABLE会被多次调用。
    比如你发一个512字节的数据,接收端可能第一次调用serialEvent(SerialPortEvent.DATA_AVAILABLE)时,
    你的int numBytes = inputStream.read(readBuffer);能收到8个字节,
    然后接收端又重新触发DATA_AVAILABLE,导致serialEvent被再次调用。
    循环直到512字节被接收完。我也遇到这个问题了,还没想到怎么解决,用
                            while((ch = is.read()) == -1)) {
                     bt[0] = (byte) ch;
                     baos.write(bt);
                    }
    也不行,因为is.read()把数据读完后,似乎就阻塞掉了。可能是要设定treshhold和接收时间,但我没找到哪里可以设定。
      

  4.   

    我的解决方法是在报文前附加一个报文长度,接收端根据此长度(pkgLen)使用
    for(int i=0; i<pkgLen; i++){
        buffer[i] = (byte)is.read();
    }
    来读取。
    看了一些文档,根本原因是 Java COMM 串口的流是无法由其本身确定结束位置的,
    因此需要附加一些标志来将射线一样的流分割为线段一样的数据包。
      

  5.   

    如果发送端发送文件,可以用'\n'来判断吧?
    每接收完一行将其写入新文件,可是由于不知道长度,还是会出问题,还要用is.read()一个个读取么?
    能给一段相关接收数据的代码吗?
      

  6.   


    在这里,
    serialPort.notifyOnDataAvailable(true); 
    接受到数据以后你首先就serialPort.notifyOnDataAvailable(fslse),你可以预先获得数据长度或者自己设定一个计时器,等待数据超时才停止接收数据,接受完数据以后再serialPort.notifyOnDataAvailable(true),这个方法你试试