我的Java应用程序通过连接到COM端口的GSM调制解调器发送短信。对于COM端口通信,我使用RXTX。一切正常,除了发送长(连接)短信。
端口代码:
private final String comPortID;
private SerialPort serialPort;
private OutputStreamWriter out;
private InputStreamReader in;
public Port(String comPortID)
{
this.comPortID = comPortID;
}
public void open() throws Exception
{
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(comPortID);
serialPort = (SerialPort) portId.open("SMS Transceiver", 100);
serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
out = new OutputStreamWriter(serialPort.getOutputStream(), "ISO-8859-1");
in = new InputStreamReader(serialPort.getInputStream(), "ISO-8859-1");
System.out.println("Port " + comPortID + " opened successfully");
}
public void write(String s) throws Exception
{
out.write(s);
out.flush();
System.out.println("Write to port: " + s);
}
public void write(char[] s) throws Exception
{
out.write(s);
out.flush();
System.out.println("Write to port: " + new String(s));
}
public void writeln(String s) throws Exception
{
out.write(s);
out.write('\r');
out.flush();
System.out.println("Write to port: " + s);
}
public String read() throws Exception
{
final long timeout = System.currentTimeMillis() + 3000;
do
{
Thread.sleep(100);
} while (!in.ready() && System.currentTimeMillis() < timeout);
final StringBuilder answer = new StringBuilder();
for (int i = 0; i < 10; i++)
{
while (in.ready())
{
int n = in.read();
if (n != -1)
{
char c = (char) n;
answer.append(c);
Thread.sleep(1);
}
else
{
break;
}
}
Thread.sleep(100);
}
System.out.println("Read from port: " + answer);
return answer.toString();
}
public void close()
{
try
{
serialPort.close();
System.out.println("Port closed");
}
catch (Exception e)
{
e.printStackTrace();
}
}
发送长短信的代码:
// Set message format to PDU mode
port.writeln("AT+CMGF=0");
port.read();
for (int i = 0; i < textParts.size(); i++)
{
System.out.println("\nSend SMS " + (i + 1) + " of " + textParts.size() + "\n");
final byte[] pdu = PDUUtils.getPDUPart(dialno, textParts.get(i), DataCodingScheme.UCS2, i + 1, textParts.size());
final char[] pduHex = PDUUtils.toHexString(pdu);
port.writeln("AT+CMGS=" + pdu.length);
port.read();
port.write("00");
port.write(pduHex);
port.write("\u001A"); // Ctrl-Z
port.read();
}
问题不在于创建PDU或AT命令。当我使用PUTTY连接到COM端口并向调制解调器发送完全相同的命令时,消息将被正确发送,并将作为一个SMS在我的手机上正确接收。所以必须有时间或配置问题。
我没有收到错误消息或异常。 read()方法接收的信息总是与我之前通过write()方法写的字符串相同。除了最后一条消息的最后一次读取()(长短信分为两部分)。我得到了不同的结果。主要是String&#34; AA&#34;或&#34; AAA&#34;返回,有时我通过write()方法写的字符串。在所有情况下,我的手机都没有收到短信。
发送短信时没有普遍问题。当我发送两个没有连接的短信(仍处于PDU模式)时,everthing工作正常。
有人可以帮帮我吗?