问题:
有时候不能发送短信?出现异常:
Example: Send message from a serial gsm modem.
SMSLib: A Java API library for sending and receiving SMS via a GSM modem
or other supported gateways.
Web Site: http://smslib.org
This software is distributed under the terms of the Apache v2.0 License.
Version: 3.3.0-b2
org.smslib.GatewayException: GSM: Invalid CREG response.
at org.smslib.modem.AModemDriver.waitForNetworkRegistration(AModemDriver.java:396)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:149)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:111)
at org.smslib.Service$1Starter.run(Service.java:227)
sim卡是用的联通的,环境正确了 ,有时候能发送,速度也还比较快。
package com.messagePlat.sms.service;
import java.util.Enumeration;
import java.util.List;
import javax.comm.CommPortIdentifier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smslib.AGateway;
import org.smslib.IInboundMessageNotification;
import org.smslib.InboundMessage;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.modem.SerialModemGateway;
import com.base.service.BaseServiceImp;
/**
* 短信连接与发送
*/
public class SendSmsService extends BaseServiceImp{
private Log log=LogFactory.getLog(this.getClass());
private Service smsService;
public Service getSmsService() {
return smsService;
}
public void setSmsService(Service smsService) {
this.smsService = smsService;
}
/**
* 停止服务
*/
public void stopSmsServer(){
if(this.smsService!=null){
try {
this.smsService.stopService();
} catch (Exception e) {
e.printStackTrace();
log.error("停止服务失败!!!");
}
}
}
/**
* 启动服务
*/
public boolean startSmsServer(){
this.smsService=new Service();
Enumeration ens=CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portLd;SerialModemGateway gateway ;
OutboundNotification ot=new OutboundNotification();
ot.setBaseDaoInterface(this.getDao());ot.setTransactionManager(this.getTransaction());
while(ens.hasMoreElements()){
portLd=(CommPortIdentifier)ens.nextElement();
if(portLd.getPortType()==CommPortIdentifier.PORT_SERIAL){
try {
gateway=new SerialModemGateway(portLd.getName(), portLd.getName(), 9600, "wavecom", "17254");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin("0000");
gateway.setOutboundNotification(ot);
gateway.setInboundNotification(new IInboundMessageNotification(){
public void process(String s,MessageTypes messagetypes,InboundMessage inboundmessage) {
if(MessageTypes.INBOUND==messagetypes){
try {
SendSmsService.this.smsService.findGateway(s).deleteMessage(inboundmessage);
} catch (Exception e) {
log.error("删除消息错误!");
}
}
}
});
this.smsService.addGateway(gateway);
} catch (Exception e) {
log.error("启动COM"+portLd.getName()+"口失败!");
}
}
}
try {
this.smsService.startService();
} catch (Exception e) {
log.error("启动猫池失败!");
return false;
}
return true;
}
/**
* 发送消息循环查询数据库
*/
public void sendMessage(){
if(this.smsService!=null){
try {
Integer count =0;
List<AGateway> cl=(List<AGateway>)this.smsService.getGatewayList();
for(int i=0;i<cl.size();i++){
if(cl.get(i).isStarted()){
count++;
}
}
List list=this.selectProcedure("{call noSendMessage(?)}",new Object[]{count});
if(list!=null&&list.size()!=0&&list.get(0)!=null){
OutboundMessage msg ;Object[] obj;
for(int i=0;i<list.size();i++){
obj=(Object[])list.get(i);
msg= new OutboundMessage(obj[1].toString(),obj[2].toString());
msg.setId(obj[0].toString());
msg.setEncoding(MessageEncodings.ENCUCS2);
this.smsService.sendMessage(msg);
this.smsService.queueMessage(msg);
}
}
} catch (Exception e) {
log.error("查询要发送的短信失败!");
e.printStackTrace();
}
}
}
}
package com.messagePlat.sms.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.base.service.BaseServiceImp;
import com.messagePlat.sms.model.Sendingsmstable;
import com.messagePlat.sms.model.Smslog;
import com.messagePlat.userInfo.model.Usertable;
/**
* 短信管理
*/
public class SmsManagerService extends BaseServiceImp{
/**
* 创建短信
* content 为自己的号码
*/
public boolean createSendMessage(Integer type,String content,String sendContent,Integer typeId,Integer userId,String count)throws Exception{
switch (type) {
case 1:
this.selectProcedure("{call addSendingMessage(?,?,?,?,?)}", new Object[]{type,typeId,userId,Integer.parseInt(count),sendContent});
break;
case 2:
this.selectProcedure("{call addSendingMessage(?,?,?,?,?)}", new Object[]{type,typeId==null?0:typeId,userId,Integer.parseInt(count),sendContent});
break;
default:
if(content.lastIndexOf(",")==(content.length()-1)){
content=content.substring(0,(content.length()-1));
}
String[]str=content.split(",");
Usertable user=(Usertable)this.findUniqueBy("userid", userId, Usertable.class);
if(user.getSmsAmount()<str.length){
return false;
}else{
int readlCount=str.length-Math.round(str.length*user.getSmsFrank());
user.setSmsAmount(user.getSmsAmount()-str.length);
this.update(user);
Smslog sg=(Smslog)this.findUniqueBy("userId", userId, Smslog.class);
if(sg==null){
sg=new Smslog();sg.setMsgfact(readlCount);sg.setUserId(userId);sg.setMsgNum(str.length);
this.save(sg);
}else{
sg.setMsgNum(sg.getMsgNum()+str.length);sg.setMsgfact(sg.getMsgfact()+readlCount);
this.update(sg);
}
List list=new ArrayList();
Sendingsmstable sd;int sendCount=Math.round(str.length*user.getSmsFrank());
for(int i=0;i<sendCount;i++){
sd=new Sendingsmstable();
sd.setNewFlag(1);sd.setPhoneNumber(str[i]);sd.setSmsConten(sendContent);sd.setUserId(userId);sd.setSmsTime(new Date());
list.add(sd);
}
this.save(list);
}
break;
}
return false;
}
/**
* 得到行业类型
*/
public List getAllType(){
try {
return this.selectProcedure("{call getSYStype()}", null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.messagePlat.sms.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.smslib.OutboundMessage.MessageStatuses;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.base.dao.BaseDaoInterface;
import com.base.transactionManager.ManualTransactionManager;
/**
* 发送消息回调
*/
public class OutboundNotification implements IOutboundMessageNotification{
private BaseDaoInterface baseDaoInterface;
private ManualTransactionManager transactionManager;
private Log log=LogFactory.getLog(this.getClass());
public void process(String arg0, OutboundMessage arg1) {
if(arg1.getMessageStatus()==MessageStatuses.SENT){
log.info("消息编号:"+arg1.getId()+"发送成功");
//修改数据库消息状态
HibernateTransactionManager trama=this.transactionManager.getTransactionManager();
DefaultTransactionDefinition d=new DefaultTransactionDefinition();
d.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_DEFAULT);
d.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status=trama.getTransaction(d);
try {
this.baseDaoInterface.updateByIds("update Sendingsmstable set newFlag=0 where smsIndex=?", Integer.parseInt(arg1.getId()));
trama.commit(status);
} catch (Exception e) {
e.printStackTrace();
trama.rollback(status);
}
}
}
public BaseDaoInterface getBaseDaoInterface() {
return baseDaoInterface;
}
public void setBaseDaoInterface(BaseDaoInterface baseDaoInterface) {
this.baseDaoInterface = baseDaoInterface;
}
public ManualTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(ManualTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
}
任务启动COM口
<bean id="checkSendMessage" class="com.messagePlat.sms.action.CheckSendMessage"></bean>
<bean id="diao" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="checkSendMessage"/>
</property>
<property name="period">
<value>10000</value>
</property>
<property name="delay">
<value>100000</value>
</property>
</bean>
数据库代码:
--触发器 和存储过程
if exists (select [name] from sysobjects where [name]='sms_chf')
drop trigger sms_chf
go
create trigger sms_chf on sendingsmstable for update
as
declare @smsuser int
begin
if update (newflag)
begin
select @smsuser=userId from inserted
insert into sentsmstable(phonenumber,smsConten,userId)
select phonenumber,smsConten,userId from inserted
delete sendingsmstable where smsindex=(select smsindex from inserted)
end
end
go
--查询没有发送的短信
if exists (select [name] from sysobjects where [name]='noSendMessage')
drop procedure noSendMessage
go
create procedure noSendMessage
@count int
as
declare @sql varchar(2000)
begin
set @sql='select top '+rtrim(ltrim(str(@count)))+' smsIndex,phoneNumber,smsConten from sendingsmstable order by smsIndex desc'
exec (@sql)
end
go
--短信新增
if exists (select [name] from sysobjects where [name]='addSendingMessage')
drop procedure addSendingMessage
go
create procedure addSendingMessage
@type int,
@typeid int,
@userId int,
@count int,
@content varchar(2000)
as
declare @usersmsAmount int , @smsFrank float,@realcount int
begin
select @usersmsAmount=smsAmount from usertable where [userid]=@userId
if(@usersmsAmount<@count) select 0
else
begin
select @smsFrank=smsFrank from usertable where [userid]=@userId
if (@type=1)
begin
declare @c1 int ,@sql1 varchar(2000)
select @c1=count(phoneid) from phone where typeid=@typeid
if(@c1<@count)
begin
set @count=@c1
update usertable set smsAmount=smsAmount-@c1 where [userid]=@userId
end
else
update usertable set smsAmount=smsAmount-@count where [userid]=@userId
set @sql1 = 'insert into sendingsmstable (userId,phoneNumber,smsConten) select top '+ltrim(rtrim(str(round(@smsFrank*@count,0))))+' '+ltrim(rtrim(str(@userId)))+',phoneNumber,'''+@content+''' from phone where typeid= '+ltrim(rtrim(str(@typeid)))+' order by newid()'
exec (@sql1)
end
if(@type=2)
begin
declare @c2 int ,@sql2 varchar(2000)
select @c2=count(phoneid) from userPhone
if(@c2<@count)
begin
set @count=@c2
update usertable set smsAmount=smsAmount-@c2 where [userid]=@userId
end
else
update usertable set smsAmount=smsAmount-@count where [userid]=@userId
set @sql2 = 'insert into sendingsmstable (userId,phoneNumber,smsConten) select top '+ltrim(rtrim(str(round(@smsFrank*@count,0))))+' '+ltrim(rtrim(str(@userId)))+',phoneNumber,'''+@content+''' from userPhone order by newid()'
exec(@sql2)
end
set @realcount=@count-round(@smsFrank*@count,0)
if exists(select smsid from smslog where userId=@userId)
update smslog set msgNum=msgNum+@count,msgfact=msgfact+@realcount
else
insert smslog (userId,msgNum,msgfact) values (@userId,@count,@realcount)
select 1
end
end
go
程序是通过读取数据去去取得短信,然后调用发送方法!
相关推荐
开发短信软件用的包,短信猫,J2ME等都可以用 短信包 jar包 开发包 smslib javacomm20-win32.zip
短信猫开发smslib源码,方便了解smslib。jar里面的类以及类里面是属性。
包括smslib开发包,32和64位串口驱动、实例源代码
SMSLib指南以及开发包,工具包,教程比较全面,技术文档转自so1127的专栏
最新版的smslib,手机发送短信非常方便
smslib开发库最新版本,原作者已不再更新并在网络上删除了所有下载资源,这份资源相当宝贵!
在java下利用smslib的二次开发包使用短信猫进行短信收发,该资源包括smslib-3.3.0b2.jar,win32com.dll,javax.comm.properties,comm.jar,短信收发的两个示例文件以及简略的使用说明,具体的使用可以参考...
sms开发包,有原程序,共大家学习
SMSLIB+RXTX 短信猫开发模块 已经在xp和centos_6_x86_64上运行成功 理论上支持所有的系统 已经包含所有的jar包和不同系统所需的so或dll
Sending and receiving of SMS using Java
smslib3.4.5的源码。smslib是java语言开发的操作短信猫gsm modem的开源库,好用,不过该版本里面需要完善的东西很多,代码中todo的注释也很多,可供开发时调试使用。
msg = new OutboundMessage("+306948494037", "Hello from SMSLib!"); srv.sendMessage(msg); System.out.println(msg); // Or, send out a WAP SI message. //OutboundWapSIMessage wapMsg = new ...
SMSLib一个很有用的程序,有服务平台和收发平台
smslib使用rxtx发短信需要的jar,commons-net-3.0.1.jar ,jsmpp-2.1.0.jar,log4j-1.2.16.jar,RXTXcomm.jar, slf4j-api-1.6.3.jar,slf4j-log4j12-1.6.3.jar, smslib-3.5.2.jar
SMSLib是一个开放源代码的短信猫二次开发包,有JAVA和.Net两个版本,目前最新版为v3.5.2,GSM模块中短信的读取和发送
SMSLIB+RXTX 短信猫开发模块 已经在win7和win server 2012上运行成功 理论上支持所有的系统 已经包含所有的jar包和不同系统所需的so或dll
smslib 短信开发包 可以用短信开发,java语言,里含smsserver,多线程处理,多种接口方式
smslib-3.4.1.jar
smslib-3.5.0.jar