Well, you’ve opened the port. But how do you clean up your mess once you’ve done with the serial port ?
Here’s some hints to clean up your serial port mess
public void disconnect() {
if (serialPort != null) {
try {
// close the i/o streams.
outStream.close();
inStream.close();
} catch (IOException ex) {
// don't care
}
// Close the port.
serialPort.close();
}
}
How close a port with java Comm ?
My problem is that multiple thread can access to a specific port and if a thread try to access, for example to COM1 then the current thread that owns the COM1 must release the port.
You have some ideas how manage this ?
Thanks.
Comment by carlo — January 25, 2009 @ 5:48 am
I think Java Comm is similar with rxtx, both have the same interface, so the example should work.
You should create a singleton as serial port arbiter. Therefore, if several threads want to access the serial port, it can ask the arbiter to grant their request. Therefore, no need to open/close serial port every time a different thread wants to access the serial port.
Comment by kunilkuda — January 28, 2009 @ 11:06 am
Synchronize your primary methods that use the port. That will prevent the close in the middle of the other method using the port.
Comment by George — January 30, 2010 @ 12:07 pm
how to close several serial ports, with just one button hit?
Comment by thariq — August 13, 2010 @ 9:53 am
When I try to close the connection as:
try{
if (serialPort != null){
inputStream.close();
serialPort.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
It throws null pointer exception on removeSerialEventListner. I did not add any serialevent to read..
Please help..
Comment by saikrishna — October 15, 2010 @ 9:43 pm
If you continuously receiving data from serialport, you will notice that you are not able to close the port, but these code snippet seems to do the job. Good luck
public void closePort() { System.out.println("Closing: " + portId.getName()); new Thread(){ @Override public void run(){ try{ inputStream.close(); serialPort.close(); }catch (IOException ex) {} } }.start(); }Comment by Behamin B — November 18, 2010 @ 7:39 pm
[...] http://embeddedfreak.wordpress.com/2008/08/08/how-to-close-serial-port-in-rxtx/ [...]
Pingback by Serial Communication in Java with Example Program « Henry Poon's Blog — January 2, 2011 @ 9:46 am