我們有需要一臺服務器(使用套接字)有與連接到它的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個。
期待一個答覆:)