我有一个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