我正在尝试使用以下方法关闭Comm端口:
public synchronized void closeComportButtonActionPerformed(
java.awt.event.ActionEvent evt) {
try {
twoWaySerCom.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
我的断开是这样的:
void disconnect() throws Exception {
if (serialPort != null) {
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
try {
// close the i/o streams.
in.close();
out.close();
} catch (IOException ex) {
// don't care
}
// Close the port.
serialPort.close();
}
当我按下关闭按钮时,我的应用程序只是冻结,我最终在我的控制台中出现错误:
A fatal error has been detected by the Java Runtime Environment:
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00949e69, pid=7568, tid=4724
#
# JRE version: Java(TM) SE Runtime Environment (8.0_25-b18) (build 1.8.0_25-b18)
# Java VM: Java HotSpot(TM) Client VM (25.25-b02 mixed mode, sharing windows-x86 )
# Problematic frame:
# C [rxtxSerial.dll+0x9e69]
有谁能解释我在这里做错了什么? 谢谢
答案 0 :(得分:2)
if(portInUse!=null)
{
try{
portInUse.port = (SerialPort)portInUse.portId.open(this.getClass().getName(),TIME_OUT);
portInUse.port.setSerialPortParams(baudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
comConn=this.COM_CONNECTED;
}
portInUse.input = new BufferedReader(
newInputStreamReader(portInUse.port.getInputStream())
);
portInUse.output = portInUse.port.getOutputStream();
//adding listeners to input and output streams
portInUse.port.addEventListener(this);
portInUse.port.notifyOnDataAvailable(true);
portInUse.port.notifyOnOutputEmpty(true);
currentPort=portInUse;
}
portInUse的数据类型:
private class CustomPort
{
String portName;
CommPortIdentifier portId;
SerialPort port;
BufferedReader input;
OutputStream output;
Scanner inputName;
}
CustomPort currentPort=new CustomPort();
和我使用的刷新功能:
public void flush()
{
try {
this.currentPort.output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我使用的关闭功能:
public void close(){
if(currentPort.port!=null){
currentPort.port.close(); //close serial port
currentPort.input = null; //close input and output streams
currentPort.output = null;
}
}
如何关闭端口:
this.flush();
this.close();
多次测试,重复测试,效果很好。
答案 1 :(得分:1)
以下部分解决了这个问题。我现在可以成功关闭一次端口。 如果我重新打开te端口,然后再次尝试关闭它,则会发生同样的错误。
try {
serialPort.removeEventListener();
serialPort.close();
in.close();
out.close();
} catch (IOException ex) {
// don't care
}
// Close the port.
serialPort.close();
}
答案 2 :(得分:0)
我发现,诀窍是让您编写的 close 方法在单独的线程中执行。我试图在主线程中发出 serialPort.close() 并且我总是会得到奇怪的错误,但是我所做的只是采用完全相同的方法并将其放入一个线程中,它完美地工作:
public void disconnectSerial() {
new Thread(() -> {
if (serialPort != null) {
try {
serialPort.getInputStream().close();
serialPort.getOutputStream().close();
serialPort.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}