---
title: "SMSLib实现Java短信收发的功能(转)"
author: "langyan"
date: "2012-05-03T11:31:20Z"
tags: []
categories: ["编程语言"]
slug: "smslib-java"
draft: false
lastmod: "2012-05-03T11:31:20Z"
id: 1508450
url: "https://langyan.iteye.com/blog/1508450"
---

摘选:http://sjsky.iteye.com/blog/1045502 

用java实现短信收发的功能，目前一般项目中短信群发功能的实现方法大致有下面三种：

- 1、 向运行商申请短信网关，不需要额外的设备，利用运行商提供的API调用程序发送短信，适用于大型的通信公司。
- 2、 借助像GSM MODEM之类的设备（支持AT指令的手机也行），通过数据线连接电脑来发送短信，这种方法比较适用于小公司及个人。要实现这种方式必须理解串口通信、AT指令、短信编码、解码。
- 3、 借助第三方运行的网站实现，由网站代发短信数据，这种方法对网站依赖性太高，对网络的要求也比较高。

       鉴于项目的情况和多方考虑，同时又找到了一个开源的SMSLib项目的支持，比较倾向于第二种方法，SMSLib的出现就不需要我们自己去写底层的AT指令，这样就可以直接通过调用SMSLib的API来实现通过GSM modem来收发送短信了。

SMSLib官方网站：[http://smslib.org/](http://smslib.org/) ，使用SMSLib的一些基本要点：

- SUN JDK 1.6 or newer. （Java环境）
- Java Communications Library. （Java串口通信）
- Apache ANT for building the sources. （编译源码时需要的）
- Apache log4j. （日志工具）
- Apache Jakarta Commons - NET. （网络操作相关的）
- JSMPP Library （SMPP协议时需要的）

有关Java串口通信需要补充说明：

- window系统可以用SUN Java Comm v2. （该版本好像也支持solaris）          其下载地址：[http://smslib.googlecode.com/files/javacomm20-win32.zip](http://smslib.googlecode.com/files/javacomm20-win32.zip)
- 其他操作系统(比如：Linux, Unix, BSD,等等),你可以选择 Java Comm v3 或者是RxTx。          Java Comm v3下载地址：[http://java.sun.com/products/javacomm/](http://java.sun.com/products/javacomm/) （需要注册）；  
           RxTx官网：[http://users.frii.com/jarvi/rxtx/index.html](http://users.frii.com/jarvi/rxtx/index.html) or [http://rxtx.qbang.org/wiki/index.php/Main\_Page](http://rxtx.qbang.org/wiki/index.php/Main_Page)

附件提供相关下载：

- java串口通信v2：[javacomm20-win32.zip](http://dl.iteye.com/topics/download/caac2045-b9f8-30ba-be34-2037978ddb29)
- [smslib-3.5.1.jar](http://dl.iteye.com/topics/download/fa833d00-ec43-3465-b4df-280fb6754269)
- 短信 modem驱动：[PL2303\_Prolific\_DriverInstaller\_v130.zip](http://dl.iteye.com/topics/download/e97e95a3-cc4b-37ee-86f0-f713f7b6218c)

本次测试的环境是window，GSM modem是wavecom，所以这次主要描述window环境下简单的实现过程：  
【一】、配置相应的环境  
      首先解压下载的Java Comm v2文件javacomm20-win32.zip，具体配置步骤如下：

- 把文件：comm.jar copy 到目录：&lt;JDKDIR&gt;/jre/lib/ext/，当然这一步也可以不要这样做，你只需把comm.jar copy到所要运行的项目对应的lib/下既可
- 把文件：javax.comm.properties copy 到目录：&lt;JDKDIR&gt;/jre/lib/
- 把DLL文件：win32com.dll（windows） copy 到目录：&lt;JDKDIR&gt;/jre/bin/
- 如果存在JRE目录, 最好按照上面步骤把文件copy到&lt;JREDIR&gt;相应的目录下

【二】、测试串口端口程序：  
TestGetPortList.java

Java代码  [![收藏代码](http://sjsky.iteye.com/images/icon_star.png)]()

01. package  michael.comm.serial;
02. import  java.util.Enumeration;
03. import  javax.comm.CommDriver;
04. import  javax.comm.CommPortIdentifier;
05. import  javax.comm.SerialPort;
06. /\**
07. * @author michael
08. \*
09. \*/
10. public   class  TestGetPortList {
11. /\**
12. * @param args
13. * @throws Exception
14. \*/
15. public   static   void  main(String\[] args)  throws  Exception {
16. // 人工加载驱动
17. // MainTest.driverInit();
18. TestGetPortList.getCommPortList();
19. // 人工加载驱动获取端口列表
20. // TestGetPortList.getPortByDriver();
21. }
22. /\**
23. * 手工加载驱动&lt;br&gt;
24. * 正常情况下程序会自动加载驱动，故通常不需要人工加载&lt;br&gt;
25. * 每重复加载一次，会把端口重复注册，CommPortIdentifier.getPortIdentifiers()获取的端口就会重复
26. \*/
27. public   static   void  driverManualInit() {
28. String driverName = "com.sun.comm.Win32Driver" ;
29. String libname = "win32com" ;
30. CommDriver commDriver = null ;
31. try  {
32. System.loadLibrary("win32com" );
33. System.out.println(libname + " Library Loaded" );
34. commDriver = (javax.comm.CommDriver) Class.forName(driverName)
35. .newInstance();
36. commDriver.initialize();
37. System.out.println("comm Driver Initialized" );
38. } catch  (Exception e) {
39. System.err.println(e);
40. }
41. }
42. /\**
43. * 获取端口列表
44. \*/
45. public   static   void  getCommPortList() {
46. CommPortIdentifier portId;
47. Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
48. while  (portEnum.hasMoreElements()) {
49. portId = (CommPortIdentifier) portEnum.nextElement();
50. if  (portId.getPortType() == CommPortIdentifier.PORT\_SERIAL) {
51. System.out.println("串口: name-"  + portId.getName()
52. + " 是否占用-"  + portId.isCurrentlyOwned());
53. } else  {
54. System.out.println("并口: name-"  + portId.getName()
55. + " 是否占用-"  + portId.isCurrentlyOwned());
56. }
57. }
58. System.out.println("-------------------------------------" );
59. }
60. /\**
61. \*
62. \*/
63. public   static   void  getPortByDriver() {
64. String driverName = "com.sun.comm.Win32Driver" ;
65. String libname = "win32com" ;
66. CommDriver commDriver = null ;
67. try  {
68. System.loadLibrary("win32com" );
69. System.out.println(libname + " Library Loaded" );
70. commDriver = (CommDriver) Class.forName(driverName).newInstance();
71. commDriver.initialize();
72. System.out.println("comm Driver Initialized" );
73. } catch  (Exception e) {
74. System.err.println(e);
75. }
76. SerialPort sPort = null ;
77. try  {
78. sPort = (SerialPort) commDriver.getCommPort("COM24" ,
79. CommPortIdentifier.PORT\_SERIAL);
80. System.out.println("find CommPort:"  + sPort.toString());
81. } catch  (Exception e) {
82. System.out.println(e.getMessage());
83. }
84. }
85. }

本机运行结果：

引用

串口: name-COM10 是否占用-false  
串口: name-COM21 是否占用-false  
串口: name-COM23 是否占用-false  
串口: name-COM20 是否占用-false  
串口: name-COM22 是否占用-false  
串口: name-COM24 是否占用-false  
串口: name-COM9 是否占用-false  
串口: name-COM19 是否占用-false  
串口: name-COM3 是否占用-false  
串口: name-COM8 是否占用-false  
串口: name-COM98 是否占用-false  
串口: name-COM99 是否占用-false  
串口: name-COM4 是否占用-false  
串口: name-COM5 是否占用-false  
串口: name-COM6 是否占用-false  
并口: name-LPT1 是否占用-false  
并口: name-LPT2 是否占用-false  
\-------------------------------------

【三】、检查串口设备信息：  
TestCommPort.java

Java代码  [![收藏代码](http://sjsky.iteye.com/images/icon_star.png)]()

01. package  michael.comm.serial;
02. import  java.io.InputStream;
03. import  java.io.OutputStream;
04. import  java.util.Enumeration;
05. import  javax.comm.CommPortIdentifier;
06. import  javax.comm.SerialPort;
07. /\**
08. * @author michael
09. \*
10. \*/
11. public   class  TestCommPort {
12. static  CommPortIdentifier portId;
13. static  Enumeration portList;
14. static   int  bauds\[] = {  9600 ,  19200 ,  57600 ,  115200  };
15. /\**
16. * @param args
17. \*/
18. public   static   void  main(String\[] args) {
19. portList = CommPortIdentifier.getPortIdentifiers();
20. System.out.println("GSM Modem 串行端口连接测试开始..." );
21. String portName = "COM24" ;
22. while  (portList.hasMoreElements()) {
23. portId = (CommPortIdentifier) portList.nextElement();
24. if  (portId.getPortType() == CommPortIdentifier.PORT\_SERIAL
25. && portName.equals(portId.getName())) {
26. System.out.println("找到串口: "  + portId.getName());
27. for  ( int  i =  0 ; i &lt; bauds.length; i++) {
28. System.out.print("  Trying at "  + bauds\[i] +  "..." );
29. try  {
30. SerialPort serialPort;
31. InputStream inStream;
32. OutputStream outStream;
33. int  c;
34. StringBuffer response = new  StringBuffer();
35. serialPort = (SerialPort) portId.open(
36. "SMSLibCommTester" ,  2000 );
37. serialPort
38. .setFlowControlMode(SerialPort.FLOWCONTROL\_RTSCTS\_IN);
39. serialPort.setSerialPortParams(bauds\[i],
40. SerialPort.DATABITS\_8, SerialPort.STOPBITS\_1,
41. SerialPort.PARITY\_NONE);
42. inStream = serialPort.getInputStream();
43. outStream = serialPort.getOutputStream();
44. serialPort.enableReceiveTimeout(1000 );
45. c = inStream.read();
46. while  (c != - 1 ) {
47. c = inStream.read();
48. }
49. outStream.write('A' );
50. outStream.write('T' );
51. outStream.write('\\r' );
52. try  {
53. Thread.sleep(1000 );
54. } catch  (Exception e) {
55. }
56. c = inStream.read();
57. while  (c != - 1 ) {
58. response.append((char ) c);
59. c = inStream.read();
60. }
61. if  (response.indexOf( "OK" ) &gt;=  0 ) {
62. System.out.print("  正在检测设备:" );
63. try  {
64. outStream.write('A' );
65. outStream.write('T' );
66. outStream.write('+' );
67. outStream.write('C' );
68. outStream.write('G' );
69. outStream.write('M' );
70. outStream.write('M' );
71. outStream.write('\\r' );
72. response = new  StringBuffer();
73. c = inStream.read();
74. while  (c != - 1 ) {
75. response.append((char ) c);
76. c = inStream.read();
77. }
78. System.out.println("  发现设备: "
79. + response.toString().replaceAll(
80. "(\\\\s+OK\\\\s+)|\[\\n\\r]" ,  "" ));
81. } catch  (Exception e) {
82. System.out.println("  检测设备失败,获取设备信息异常："
83. + e.getMessage());
84. }
85. } else  {
86. System.out.println("  检测设备失败，沒有接收到响应结果!" );
87. }
88. serialPort.close();
89. } catch  (Exception e) {
90. System.out.println("  检测设备失败，发生异常："  + e.getMessage());
91. }
92. }
93. }
94. }
95. }
96. }

运行结果如下：

引用

GSM Modem 串行端口连接测试开始...  
找到串口: COM24  
  Trying at 9600...  正在检测设备:  发现设备: AT+CGMM MULTIBAND  900E  1800  
  Trying at 19200...  发现设备失败，沒有接收到响应结果!  
  Trying at 57600...  发现设备失败，沒有接收到响应结果!  
  Trying at 115200...  发现设备失败，沒有接收到响应结果!

【四】、测试收发短信：

Java代码  [![收藏代码](http://sjsky.iteye.com/images/icon_star.png)]()

001. package  michael.sms;
002. import  java.util.ArrayList;
003. import  java.util.LinkedList;
004. import  java.util.List;
005. import  org.apache.log4j.Level;
006. import  org.apache.log4j.Logger;
007. import  org.smslib.AGateway;
008. import  org.smslib.GatewayException;
009. import  org.smslib.InboundMessage;
010. import  org.smslib.OutboundMessage;
011. import  org.smslib.Service;
012. import  org.smslib.AGateway.Protocols;
013. import  org.smslib.Message.MessageEncodings;
014. import  org.smslib.modem.SerialModemGateway;
015. /\**
016. * @author michael
017. \*
018. \*/
019. public   class  SmsHandler {
020. private   static   final  Logger logger = Logger.getLogger(SmsHandler. class );
021. private  Service smsService;
022. /\**
023. \*
024. \*/
025. public  SmsHandler() {
026. smsService = Service.getInstance();
027. List&lt;AGateway&gt; agatewayList = new  ArrayList&lt;AGateway&gt;();
028. String portName = "COM24" ; //"/dev/ttyUSB0";// COM24
029. SerialModemGateway gateway = new  SerialModemGateway(
030. "modem."  + portName, portName,  9600 ,  "wavecom" ,  "PL2303" );
031. gateway.setInbound(true );
032. gateway.setOutbound(true );
033. gateway.setProtocol(Protocols.PDU);
034. gateway.setSimPin("0000" );
035. agatewayList.add(gateway);
036. try  {
037. for  (AGateway gatewayTmp : agatewayList) {
038. smsService.addGateway(gatewayTmp);
039. }
040. } catch  (GatewayException ex) {
041. logger.error(ex.getMessage());
042. }
043. }
044. /\**
045. \*
046. \*/
047. public   void  start() {
048. logger.info("SMS service start....." );
049. try  {
050. smsService.startService();
051. } catch  (Exception ex) {
052. logger.error("SMS service start error:" , ex);
053. }
054. }
055. /\**
056. \*
057. \*/
058. public   void  destroy() {
059. try  {
060. smsService.stopService();
061. } catch  (Exception ex) {
062. logger.error("SMS service stop error:" , ex);
063. }
064. logger.info("SMS service stop" );
065. }
066. /\**
067. * send SMS
068. * @param msg
069. * @return Boolean
070. \*/
071. public  Boolean sendSMS(OutboundMessage msg) {
072. try  {
073. msg.setEncoding(MessageEncodings.ENCUCS2);
074. return  smsService.sendMessage(msg);
075. } catch  (Exception e) {
076. logger.error("send error:" , e);
077. }
078. return   false ;
079. }
080. private   boolean  isStarted() {
081. if  (smsService.getServiceStatus() == Service.ServiceStatus.STARTED) {
082. for  (AGateway gateway : smsService.getGateways()) {
083. if  (gateway.getStatus() == AGateway.GatewayStatuses.STARTED) {
084. return   true ;
085. }
086. }
087. }
088. return   false ;
089. }
090. /\**
091. * read SMS
092. * @return List
093. \*/
094. public  List&lt;InboundMessage&gt; readSMS() {
095. List&lt;InboundMessage&gt; msgList = new  LinkedList&lt;InboundMessage&gt;();
096. if  (!isStarted()) {
097. return  msgList;
098. }
099. try  {
100. this .smsService.readMessages(msgList,
101. InboundMessage.MessageClasses.ALL);
102. logger.info("read SMS size: "  + msgList.size());
103. } catch  (Exception e) {
104. logger.error("read error:" , e);
105. }
106. return  msgList;
107. }
108. /\**
109. * @param args
110. \*/
111. public   static   void  main(String\[] args) {
112. Logger.getRootLogger().setLevel(Level.INFO);
113. OutboundMessage outMsg = new  OutboundMessage( "189xxxx\*\*\*\*" ,  "信息测试" );
114. SmsHandler smsHandler = new  SmsHandler();
115. smsHandler.start();
116. //发送短信
117. smsHandler.sendSMS(outMsg);
118. //读取短信
119. List&lt;InboundMessage&gt; readList = smsHandler.readSMS();
120. for  (InboundMessage in : readList) {
121. System.out.println("发信人："  + in.getOriginator() +  " 短信内容:"
122. + in.getText());
123. }
124. smsHandler.destroy();
125. System.out.println("-----------" );
126. }
127. }

发送短信亲测，手机能正常接收显示。读取设备的短信程序运行结果结果如下：

引用

INFO - Service.listSystemInformation(113) | SMSLib: A Java API library for sending and receiving SMS via a GSM modem or other supported gateways.  
This software is distributed under the terms of the Apache v2.0 License.  
Web Site: http://smslib.org  
INFO - Service.listSystemInformation(114) | Version: 3.5.1  
INFO - Service.listSystemInformation(115) | JRE Version: 1.6.0\_18  
INFO - Service.listSystemInformation(116) | JRE Impl Version: 16.0-b13  
INFO - Service.listSystemInformation(117) | O/S: Windows Vista / x86 / 6.0  
INFO - SmsHandler.start(55) | SMS service start.....  
INFO - DefaultQueueManager.init(92) | Queue directory not defined. Queued messages will not be saved to filesystem.  
INFO - ModemGateway.startGateway(188) | GTW: modem.COM24: Starting gateway, using Generic AT Handler.  
INFO - SerialModemDriver.connectPort(68) | GTW: modem.COM24: Opening: COM24 @9600  
INFO - AModemDriver.waitForNetworkRegistration(459) | GTW: modem.COM24: GSM: Registered to foreign network (roaming).  
INFO - AModemDriver.connect(175) | GTW: modem.COM24: MEM: Storage Locations Found: SMBM  
INFO - CNMIDetector.getBestMatch(142) | CNMI: No best match, returning: 1  
INFO - ModemGateway.startGateway(191) | GTW: modem.COM24: Gateway started.  
INFO - SmsHandler.readSMS(113) | read SMS size: 1  
发信人：8618918001030 短信内容:hello 回复测试  
INFO - ModemGateway.stopGateway(197) | GTW: modem.COM24: Stopping gateway...  
INFO - SerialModemDriver.disconnectPort(120) | GTW: modem.COM24: Closing: COM24 @9600  
INFO - ModemGateway.stopGateway(201) | GTW: modem.COM24: Gateway stopped.  
INFO - SmsHandler.destroy(72) | SMS service stop  
\-----------