我们有一项研究要求服务器(使用套接字)具有连接到它的 cisco 设备的 com 端口。问题是我无法初始化多个线程。
这是关于我们如何为 com 端口初始化 Thread 的代码。
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 个。
期待回复:)