Com-Port => PortInUseException....

Ronin-Jay

Erfahrenes Mitglied
Hallo zusammen,

leider hänge ich mal wieder fest. Und zwar bekomme ich plötzlich von meiner Applikation eine PortInUseException. An sich nichts ungewöhnliches, da es bedeutet, daß der Port schon belegt ist.
Ich kann es allerdings nicht ganz nachvollziehen, da ich mit einer älteren Apllikation (baut auf demselben Source auf) problemlos den Port öffnen kann.

Hier mal mein Source:
Code:
 /**
 * ......
 */ 

package ECM;


import java.awt.Toolkit;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;


//===========================================================================
//TODO:	.....
//
//===========================================================================


/**
 * 
 * @author 
 *
 */
public class Transponder implements Runnable, SerialPortEventListener{
	
	//declarations
	private static final String 		CONF_FILE = "inc/settings.conf";
	private static CommPortIdentifier 	portId;
	private static Enumeration			portList;
	private InputStream		    		in;
	private ResourceBundle 				res;
	private SerialPort		    		serialPort;
	private Thread		      			readThread,
										timeoutThread;
	private String						key = "",
    									lastKey = "",
    									defaultPort,
    									eTmpStr,
    									blockName;
	private int 	numBytes = 0,
					payload,
					baudrate,
					portNum;
	private boolean portFound = false;
	    
    
    /**
     * Constructor
     */
    public Transponder(){
    	//read conf-file
		try{
			in = ClassLoader.getSystemResourceAsStream(CONF_FILE);
		    res = new PropertyResourceBundle(in);
		} catch (IOException ioe) {
			System.err.println("Could not find settings.conf");
			System.exit(1);
		  }
		
		//set values
		payload		= Integer.valueOf( res.getString("ECM.Payload")).intValue();
		defaultPort = res.getString("ECM.DefaultPort");
		portNum 	= Integer.valueOf( res.getString("ECM.Portnumber"))
					  .intValue();
		blockName	= res.getString("ECM.Name");
		baudrate	= Integer.valueOf( res.getString("ECM.Baud")).intValue();
		
		if(checkPort()){
			//connect to COM-Port
		    try {
		    	//timeoutThread = new Thread(this);
		    	//timeoutThread.start();
				connect();
			} catch (UnsupportedCommOperationException e) {
				System.out.println("Falsche Porteinstellung!");
			  } 
			  catch (PortInUseException e) {
				  System.out.println("Port '"+defaultPort+"' bereits belegt!");
				  //timeoutThread.stop();
				  //e.printStackTrace()
	    	  }
			  catch (NullPointerException npe){}
			  catch (ExceptionInInitializerError eiie){}
			  catch (IOException e) {}
			  catch (TooManyListenersException e) {}
			  catch (Exception e){e.printStackTrace();}
		}
    }//constructor
    
    
    /**
     * 
     */
    public void run() {
    	try {
    	    Thread.sleep(2000);
    	    //System.out.println("TIMEOUT");
    	} catch (InterruptedException e) {}
	}//run()


    /**
     * handling of events from serialport
     */
	public void serialEvent(SerialPortEvent event) {
		// TODO Auto-generated method stub
		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:
				//size of package of bytes to read from inputstream
				byte[] readBuffer = new byte[16];
				String tmpStr;
				int tmpInt;

			    try {
			    	//get inputstreamdata
			    	while (in.available() > 0) {
			    		tmpInt = in.read(readBuffer);
			    		tmpStr = new String(readBuffer).trim();

			    		//don't count whitespaces - they would tamper the 
			    		//numBytes and concerning that finally the key
			    		if (!tmpStr.equals("")){
			    			numBytes += tmpInt;			    			
			    		}
					}//while		    	
			    	
			    	//build the transponder-key:
			    	key = key.concat(new String(readBuffer).trim());
			    	
			    	if (numBytes >= payload) {			    		
			    		if (!key.equals(lastKey)) {
			    			System.out.println("ermittelt: "+key);
			    			lastKey = key;
			    			
			    			//Beeps
			    			Toolkit.getDefaultToolkit().beep();
			    		}//if#2		
			    		
			    		//reset key & read bytes
			    		key = "";
			    		numBytes = 0;
			    	}//if#1
		    } catch (IOException e) {}		    
		}//switch
	}//serialEvent()
    
    
    /**
     * looking for serialport
     */
    private boolean checkPort(){
    	portList = CommPortIdentifier.getPortIdentifiers();

    	while (portList.hasMoreElements()) {
    	    portId = (CommPortIdentifier) portList.nextElement();
    	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    			if (portId.getName().equals(defaultPort)) {
    			    //System.out.println("Found port: "+defaultPort);
    			    portFound = true;
    			}//if#2 
    	    } //if#1
    	}//while 
    	
    	//no port found
    	if (!portFound) {
    	    System.out.println("Port " + defaultPort + " not found.");
    	}    	
    	return portFound;
    }//checkPort()
    
    
    /**
     * connects to the serial port -
     * all exceptions are thrown and catched in the constructor
     */
    public void connect() throws Exception{
    	//open serialport
    	serialPort = (SerialPort) portId.open(blockName, portNum);
    	    	
    	//get inputstream from serialport
    	in = serialPort.getInputStream();
		
    	//add listener to serialport
    	serialPort.addEventListener(this);
		
    	serialPort.notifyOnDataAvailable(true);
    	serialPort.setSerialPortParams(baudrate,
    			SerialPort.DATABITS_8, 
				SerialPort.STOPBITS_1, 
				SerialPort.PARITY_NONE);

    	readThread = new Thread(this);
    	readThread.start();
    }//connect()
    
 
    
    
	//========================================================================
	// help-methods
	//========================================================================
		
    /**
     * help-method to test class and see if settings were imported correctly
     */
    public void printInfos(){
    	System.out.println("Payload: " +payload);
    	System.out.println("DefaultPort: " +defaultPort);
    	System.out.println("Portnumber: " +portNum);
    	System.out.println("Baudrate: " +baudrate);
    	System.out.println("Block-Name: " +blockName);
    }//printInfos()	


	

}//class

Ich bekomme immer die Ausgabe: "Port 'Com3' bereits belegt!".
 
Zurück