コンピューターのポート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