我的3G Modem
端口上的计算机上安装了COM9
。我想从该端口读取传入的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
答案 0 :(得分:0)
我读到的文字毫无意义
那是因为你用以下无意义的代码阅读它:
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));
}