2013-02-21 62 views
0

我們有需要一臺服務器(使用套接字)有與連接到它的Cisco設備的COM端口進行研究。問題是我不能初始化多個線程。使用多線程與多串行COM端口

這是我們如何初始化一個com端口的線程的代碼。

public CLI(String portName) {  
String driverName = "com.sun.comm.Win32Driver"; 
try{ 
    CommDriver commdriver = (CommDriver)Class.forName(driverName).newInstance(); 
    commdriver.initialize(); 
}catch (Exception e2){} 
portList = CommPortIdentifier.getPortIdentifiers(); 

while (portList.hasMoreElements()) { 

    portId = (CommPortIdentifier) portList.nextElement(); 
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
     if (portId.getName().equals(portName)) { 
      try{ 
      System.out.println("Welcome to " + portId.getName() + "!!"); 

      serialPort = (SerialPort) portId.open("COM", 2000); 
      inputStream = serialPort.getInputStream(); 
      outputStream = serialPort.getOutputStream(); 
      serialPort.addEventListener(this); 
      serialPort.notifyOnDataAvailable(true); 

      serialPort.setSerialPortParams(9600, 
      SerialPort.DATABITS_8, 
      SerialPort.STOPBITS_1, 
      SerialPort.PARITY_NONE); 
      serialPort.setFlowControlMode(1); 
      }catch(Exception ex){} 

      readThread = new Thread(this); 
      readThread.start(); 
      } 
     } 
    } 
} 

public void run() { 
    } 

public void send_msg(String line){ 
     try { 
      outputStream.write((line + (char)13).getBytes()); 
      outputStream.flush(); 
     } catch (IOException e) {} 

} 

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[8]; 
    try { 
     inputStream.reset(); 
     outputStream.flush(); 
    } catch (IOException ex) { 
    } 
     try { 
      while (inputStream.available() > 0) { 
       int numBytes = inputStream.read(readBuffer); 
      } 
      Cleaner = new String(readBuffer); 

      for(int ctr = 0; ctr < 8; ctr++) 
       if((Cleaner.charAt(ctr) >= 32 && Cleaner.charAt(ctr) <= 127)) 
       { 
        receiver += Cleaner.charAt(ctr); 
        //System.out.print(Cleaner.charAt(ctr)); 
       } 
       else if(Cleaner.charAt(ctr) == (char)13){ 
        //test_prov.sendMessage(receiver); 
        test_prov.send_broadcast(receiver); 
        System.out.print(receiver); 
        receiver = ""; 
       } 

     } catch (IOException e) {} 
     break; 
    } 
} 

問題是,當我初始化其中的2個,它似乎沒有讀取其中的1個。

期待一個答覆:)

回答

0

您正在使用相同的Runnable爲每個線程。這可運行保存用於與一個COM端口進行通信的IO流。爲了處理多個端口,你必須有一組每個線程特定的IO流,即。每Runnable

處理此問題的正確方法是將處理通信的邏輯與創建線程的邏輯分開。

0

如果您不是以兆位速度進行通信,則不需要多線程 - 只需在10..100毫秒間隔內輪詢所有端口,以獲取傳入數據。