0 0

求解决方案!有开发过smslib的朋友,进来看看!30

问题:
有时候不能发送短信?出现异常:
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



程序是通过读取数据去去取得短信,然后调用发送方法!
2009年11月12日 20:05

1个答案 按时间排序 按投票排序

0 0

GatewayException: GSM: Invalid CREG response.
這個異常就是單純的指卡有問題吧,你換一個sim卡試試,記得以前遇到過類似情況

2009年11月27日 11:01

相关推荐

Global site tag (gtag.js) - Google Analytics