[英]Unable to parse actuall data from com port
我的計算機上的COM9
端口上安裝了3G Modem
。 我想從該端口讀取傳入的sms
。 我正在使用下面的代碼。
import java.io.InputStream;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
/**
*
* @author IamUsman
*/
public class ReadingPorts implements SerialPortEventListener, Runnable {
static CommPortIdentifier portId;
static Enumeration portList;
static SerialPort port;
static InputStream inputStream;
static Thread readThread;
static byte buffer[];
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM9")) {
if (!portId.isCurrentlyOwned()) {
ReadingPorts rp = new ReadingPorts();
} else {
System.out.println("This port is already used by some other program");
}
}
}
}
}
public ReadingPorts() {
try {
port = (SerialPort) portId.open("Custom", 500);
inputStream = port.getInputStream();
System.out.println("** Connected To Streams **");
port.addEventListener(this);
port.notifyOnDataAvailable(true);
port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
port.enableReceiveTimeout(500);
System.out.println("................................");
readThread = new Thread(this);
readThread.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void serialEvent(SerialPortEvent event) {
System.out.println("In Callback method");
switch(event.getEventType()){
case SerialPortEvent.DATA_AVAILABLE:
buffer = new byte[8];
try{
while (inputStream.available()>0) {
int numBytes = inputStream.read(buffer);
}
System.out.println(new String(buffer));
}catch(Exception ex){
ex.printStackTrace();
}
break;
}
}
@Override
public void run() {
try {
Thread.sleep(500);
} catch (Exception ex) {
ex.printStackTrace();;
}
}
}
我正在讀取數據,但這很有意義。 我讀的東西如下
+CMTI: "SM",14
我讀的文字沒有意義
那是因為您使用以下無意義的代碼來閱讀它:
while (inputStream.available()>0) {
int numBytes = inputStream.read(buffer);
}
System.out.println(new String(buffer));
它應該是:
while (inputStream.available()>0) {
int numBytes = inputStream.read(buffer);
System.out.println(new String(buffer, 0, numBytes));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.