-1
이 코드는 COM 포트에 쓰고 읽을 수 있습니다.Java javax.comm syncronous read
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
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;
public class MainClass implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// if (portId.getName().equals("COM1")) {
if (portId.getName().equals("/dev/term/a")) {
MainClass reader = new MainClass();
}
}
}
}
public MainClass() {
try {
serialPort = (SerialPort) portId.open("MainClassApp", 2000);
} catch (PortInUseException e) {
}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
readThread = new Thread(this);
readThread.start();
/*HERE I NEED TO WAIT THE ANSWER*/
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException 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[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
}
하지만 방법 (I가 자리를 어디에 두 참조), 나는 syncronous 읽기 같은 필요를 종료하기 전에 대답을 기다릴 필요, 그것을 어떻게 할까?
코드가 약간 손상되었습니다. 스레딩 및 이벤트를 수행 할 필요가 없습니다. 직렬 포트 출력 스트림에 쓰고 입력 스트림에서 읽지 않는 이유는 무엇입니까? 동기화됩니다. 비동기가 실제로 필요한 경우 worl에 있습니다 – DomV
하지만 inputstream이 데이터를 수신하는 시점을 알 수 없습니다 ... 프린터가 응답 할 때까지 주 스레드를 중지하는 방법은 무엇입니까? – Tobia