import java.io.*;
import java.util.*;
import gnu.io.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.*;
import java.awt.event.*;public class test extends JFrame implements ActionListener,SerialPortEventListener
{
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString;
static SerialPort serialPort;
static InputStream inputStream;
static boolean outputBufferEmptyFlag = false;
JScrollPane p1;
JTextField port=new JTextField(10);
JButton ok=new JButton("open");
JTextArea area=new JTextArea(15,10);
JLabel l2=new JLabel("port:");
JButton read=new JButton("read");
/**
* Method declaration
*
*
* @param args
*
* @see
*/
test()
{
setTitle("SerialCom");
setVisible(true);
setLayout(null);
p1=new JScrollPane(area);
add(port);port.setBounds(120,30,150,25);
add(l2);l2.setBounds(35,30,100,25);
add(ok);ok.setBounds(300,30,80,23);
add(read);read.setBounds(150, 80, 80, 25);
add(p1);p1.setBounds(35,120,340,250);
ok.addActionListener(this);
read.addActionListener(this);
setSize(400,400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(true);
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width)/4,(screen.height)/4);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
serialPort.close();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ok)
{
boolean portFound = false;
String useport = port.getText();
area.append("choose port:");
area.append(useport);
area.append("\n");
System.out.println("choose port:"+useport);
String defaultPort = "/dev/"+useport; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equalsIgnoreCase(defaultPort)) {
area.append("Found port:");
area.append( defaultPort);
area.append("\n");
System.out.println("Found port " + defaultPort); portFound = true; try {
serialPort = (SerialPort) portId.open("test", 200000);
}
catch (PortInUseException ex) {
area.append("Port in use!");
area.append("\n");
System.out.println("Port in use."); continue;
} try {
serialPort.setSerialPortParams(115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException ex) {}
}
}
} if (!portFound) {
area.append("port ");
area.append(defaultPort);
area.append("not found!");
area.append("\n");
System.out.println("port " + defaultPort + " not found.");
}
}
else if(e.getSource()==read)
{
area.append("wait for msg:");
area.append("\n");
try
{
serialPort.addEventListener(this);
}
catch(TooManyListenersException a){}
serialPort.notifyOnDataAvailable(true);
try
{
inputStream=serialPort.getInputStream();
}
catch(IOException a){}
}
}
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[200];
try
{
String fileName = null;
while(inputStream.available()>0)
{
area.append("there are data available in the port");
area.append("\n");
int numBytes=inputStream.read(readBuffer);
fileName = "/root/data.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
try{
String str = new String(readBuffer);
bw.write(str); //写入
bw.newLine();
}
catch(IOException e){ }
area.append(new String(readBuffer));
bw.close();
}
}
catch(IOException e){}
break;
}
}
public static void main(String[] args)
{
new test();
}
}此界面运行于pc a,选择了port,open后,点击read按钮,当另一个pc b发数据的时候,可以正确接收并写入文件。
但加入一个write按钮,点击此按钮后向b发送命令“ask for reply”,b接收到后向a发送“13900100400”,可a接收的全是乱码。代码如下:
import java.util.*;
import gnu.io.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.*;
import java.awt.event.*;public class test extends JFrame implements ActionListener,SerialPortEventListener
{
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString;
static SerialPort serialPort;
static InputStream inputStream;
static boolean outputBufferEmptyFlag = false;
JScrollPane p1;
JTextField port=new JTextField(10);
JButton ok=new JButton("open");
JTextArea area=new JTextArea(15,10);
JLabel l2=new JLabel("port:");
JButton read=new JButton("read");
/**
* Method declaration
*
*
* @param args
*
* @see
*/
test()
{
setTitle("SerialCom");
setVisible(true);
setLayout(null);
p1=new JScrollPane(area);
add(port);port.setBounds(120,30,150,25);
add(l2);l2.setBounds(35,30,100,25);
add(ok);ok.setBounds(300,30,80,23);
add(read);read.setBounds(150, 80, 80, 25);
add(p1);p1.setBounds(35,120,340,250);
ok.addActionListener(this);
read.addActionListener(this);
setSize(400,400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(true);
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width)/4,(screen.height)/4);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
serialPort.close();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ok)
{
boolean portFound = false;
String useport = port.getText();
area.append("choose port:");
area.append(useport);
area.append("\n");
System.out.println("choose port:"+useport);
String defaultPort = "/dev/"+useport; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equalsIgnoreCase(defaultPort)) {
area.append("Found port:");
area.append( defaultPort);
area.append("\n");
System.out.println("Found port " + defaultPort); portFound = true; try {
serialPort = (SerialPort) portId.open("test", 200000);
}
catch (PortInUseException ex) {
area.append("Port in use!");
area.append("\n");
System.out.println("Port in use."); continue;
} try {
serialPort.setSerialPortParams(115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException ex) {}
}
}
} if (!portFound) {
area.append("port ");
area.append(defaultPort);
area.append("not found!");
area.append("\n");
System.out.println("port " + defaultPort + " not found.");
}
}
else if(e.getSource()==read)
{
area.append("wait for msg:");
area.append("\n");
try
{
serialPort.addEventListener(this);
}
catch(TooManyListenersException a){}
serialPort.notifyOnDataAvailable(true);
try
{
inputStream=serialPort.getInputStream();
}
catch(IOException a){}
}
}
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[200];
try
{
String fileName = null;
while(inputStream.available()>0)
{
area.append("there are data available in the port");
area.append("\n");
int numBytes=inputStream.read(readBuffer);
fileName = "/root/data.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
try{
String str = new String(readBuffer);
bw.write(str); //写入
bw.newLine();
}
catch(IOException e){ }
area.append(new String(readBuffer));
bw.close();
}
}
catch(IOException e){}
break;
}
}
public static void main(String[] args)
{
new test();
}
}此界面运行于pc a,选择了port,open后,点击read按钮,当另一个pc b发数据的时候,可以正确接收并写入文件。
但加入一个write按钮,点击此按钮后向b发送命令“ask for reply”,b接收到后向a发送“13900100400”,可a接收的全是乱码。代码如下:
import java.util.*;
import gnu.io.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.*;
import java.awt.event.*;
public class test extends JFrame implements ActionListener,SerialPortEventListener
{
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString;
static SerialPort serialPort;
static InputStream inputStream;
static OutputStream outputStream;//111
static boolean outputBufferEmptyFlag = false;
JScrollPane p1;
Thread readThread = new Thread();//111
JButton write = new JButton("write");//111
JTextField port=new JTextField(10);
JButton ok=new JButton("open");
JTextArea area=new JTextArea(15,10);
JLabel l2=new JLabel("port:");
JButton read=new JButton("read");
test()
{
setTitle("SerialCom");
setVisible(true);
setLayout(null);
p1=new JScrollPane(area);
add(port);port.setBounds(120,30,150,25);
add(l2);l2.setBounds(35,30,100,25);
add(ok);ok.setBounds(300,30,80,23);
add(read);read.setBounds(150, 80, 80, 25);
add(write);write.setBounds(150, 120, 80, 25);//111
add(p1);p1.setBounds(35,120,340,250);
ok.addActionListener(this);
read.addActionListener(this);
write.addActionListener(this);//111
setSize(400,400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(true);
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width)/4,(screen.height)/4);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
serialPort.close();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ok)
{
boolean portFound = false;
String useport = port.getText();
area.append("choose port:");
area.append(useport);
area.append("\n");
String defaultPort = "/dev/"+useport; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equalsIgnoreCase(defaultPort)) {
area.append("Found port:");
area.append( defaultPort);
area.append("\n");
System.out.println("Found port " + defaultPort); portFound = true; try {
serialPort = (SerialPort) portId.open("test", 200000);
}
catch (PortInUseException ex) {
area.append("Port in use!");
area.append("\n");
System.out.println("Port in use."); continue;
} try {
serialPort.setSerialPortParams(115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException ex) {}
}
}
} if (!portFound) {
area.append("port ");
area.append(defaultPort);
area.append("not found!");
area.append("\n");
}
}
else if(e.getSource()==read)
{
area.append("wait for msg:");
area.append("\n");
try
{
serialPort.addEventListener(this);
}
catch(TooManyListenersException a){}
serialPort.notifyOnDataAvailable(true);
try
{
inputStream=serialPort.getInputStream();
}
catch(IOException a){}
}
else if(e.getSource()==write)//222
{
String message = "ask for reply";
try {
outputStream.write(message.getBytes());
}
catch (IOException ex) {}
area.append("write message:");
area.append(message);
area.append("\" to the port\n");
try
{
serialPort.addEventListener(this);
}
catch(TooManyListenersException a){}
serialPort.notifyOnDataAvailable(true);
try
{
inputStream=serialPort.getInputStream();
}
catch(IOException a){}
readThread=new Thread(this);
readThread.start();
}//222 }
{
try
{
Thread.sleep(6000);
}
catch(InterruptedException e){}
}}//222
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[200];
try
{
String fileName = null;
while(inputStream.available()>0)
{
area.append("there are data available in the port");
area.append("\n");
int numBytes=inputStream.read(readBuffer);
fileName = "/root/data.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
try{
String str = new String(readBuffer);
bw.write(str); //写入
bw.newLine();
}
catch(IOException e){ }
area.append(new String(readBuffer));
bw.close();
}
}
catch(IOException e){}
break;
}
}
public static void main(String[] args)
{
new test();
}
}增加的代码如1111单行,以及222之间标示的部分所示,只是在添加的write按钮actionPerformed中先write后read,并起用了线程,就读出乱码,难道不能同时先写后读?是thread sleep的时间不够,还是为test线程open port的时间不够?
如果能虚拟一个最好,能提供“串口调试器+加一个虚拟串口的小工具”的下载地址么?
主要是怀疑线程应用的不对,是thread sleep的时间不够,还是为test线程open port的时间不够?
相对来说串口调试器要更好找一些
我的意思是最好确认你的哪部分程序有问题lz用得都是
static InputStream inputStream;
static OutputStream outputStream;//111
静态的变量啊感觉这个可能会有点影响啊
我把static去掉,仍然出现这种状况,是不是写入文件的时候FileWriter 要换成OutputStream?
另外,我想在串口接收完一行再写入文件,以下代码:case SerialPortEvent.DATA_AVAILABLE:
int newData = 0;
StringBuffer cString = new StringBuffer();
try {
String fileName = null;
while (newData != -1) {
area.append("there are data available in the port");
area.append("\n");
try{
newData = inputStream.read();
if(newData == -1)
break;
if('\n' == (char)newData){
}else{
cString.append((char)newData);
}
}
catch(IOException ex){
System.err.println(ex);
return;
}
}
}
catch (IOException e) {
}
break;
应该可以实现吧?(目前虚拟串口还未建立)