我们有一项研究要求服务器(使用套接字)具有连接到cisco设备的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 :(得分:0)
您对每个帖子使用相同的Runnable
。该runnable保存用于与一个COM端口通信的IO流。要处理多个端口,每个线程必须有一组特定的IO流,即。每Runnable
。
处理此问题的正确方法是将处理通信的逻辑与创建线程的逻辑分开。
答案 1 :(得分:0)
如果您没有以兆比特速度进行通信,则不需要多线程 - 只需在10..100ms间隔内轮询所有端口以获取传入数据。