说明:短信的的用处越来越多,对短信的内容有所增加,以前老模式下的短短信已经满足不了日常的需求了,所以三点运营商升级了3.0版本协议,3.0版本协议最大的改进之处就是支持了长短信,兼容以前2.0版本的短短信内容。近期在做项目的时候又进行了一次封装3.0协议的华为短信网关接口,之前封装的是2.0版本的,那个时候没有长短信概念,现在整理下,把我的主要代码发出来,因为整个项目已经封装成了webService接口,代码比较多,只是贴出来了主要代码,如需要完整项目,加我QQ详细聊,可以帮助远程支撑调测整个项目,但是这个需要适当给点报酬哦,因为这个需要花费时间来弄嘛,当然了如果我接了你的单肯定是要完整的把你的代码调测到正常运行的啦,废话不说啦,贴代码,如有你觉得有参考价值就给个赞,谢谢啦,我也是花了时间来开发,以及来整理这里的博客,不喜欢的绕过就行啦,勿喷。
webService接口主调用代码,首先收到请求后保存了日志,方便后续失败了重调,代码实现如下:
package com.ss.dd.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import com.starit.database.db.DBConnFactory;
import com.ustcinfo.eoms.util.SendMessage;
public class MessageService {
private Log log = LogFactory.getLog(getClass());
/**
* 发送短信
*
* @param input
* @return
* @throws SQLException
*/
public String sendShortMessage(final String SP, String count, String pwd,
final String pho, final String contect) throws SQLException {
// Document doc;
// String keyId;
if (SP.equals("") || SP.equals(null) || pho.equals("")
|| pho.equals(null) || contect.equals("")
|| contect.equals(null)) {
log.error("SP号码,pho接收号码、contect短信内网为必填项,请核实!");
return "
}
SendMessage msg = new SendMessage();
Connection conn = null;
PreparedStatement stat = null;
// ResultSet rs = null;
String phs_id = getDatePrimaryKey();
try {
conn = DBConnFactory.getDBConn().getConnection();
stat = conn.prepareStatement("insert into phs_send(phs_id,phs_no,content,phs_no_sp) values (?,?,?,?)");
stat.setString(1, phs_id);
stat.setString(2, pho);
stat.setString(3, contect);
stat.setString(4, SP);
stat.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.info("保存数据异常");
return "
} finally {
if (stat != null) {
stat.close();
}
if (conn != null) {
conn.close();
}
}
return msg.SendMsg(phs_id, SP, pho, contect);
}
/**
* 获取时间
*/
public static String getTimeYearMonthDay(String dateFormat) {
String[] strNow = new SimpleDateFormat(dateFormat).format(new Date())
.toString().split("-");
String str = "";
for (String string : strNow) {
str = str + string;
}
return str;
}
/**
* 获取位数为7位的随机数
*
* @return
* */
public static String getRandom() {
Random random = new Random();
int nextInt = random.nextInt(9000);
nextInt = nextInt + 1000;
String str = nextInt + "";
return str;
}
/**
* 生产日期主键
* @return
*/
public static String getDatePrimaryKey() {
return getTimeYearMonthDay("yyyyMMddHHmmss") + getRandom();
}
}
发送代码调用类:
package com.sss.ff.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.starit.client.SmgwClient;
import com.starit.dao.GetMsgNeedSend;
public class SendMessage {
private Log log = LogFactory.getLog(getClass());
/**
*
* @param phoneNum 手机号码
* @param msgContent 短信内容
* @return
*/
public String SendMsg(String keyId,String sp,String phoneNum, String msgContent){
String returnValue = invokeSendMsg(keyId,sp,phoneNum,msgContent);
//String desc = GetReturnMsg(returnValue);
if(returnValue.equals("发送成功")){
return "
}else{
return "
}
}
/**
* 发送短信
*
* @param phoneNum 手机号码
* @param msgContent 短信内容
* @return 成功失败标识
*/
public String invokeSendMsg(String keyId,String sp, String phoneNum, String msgContent){
String Retmsg="";
try {
//sends = GetMsgNeedSend.SelectMsgsNeedToSend();
/** for(Phs_send s:sends){
if(-1 == SmgwClient.BL_SmsClient(s)){
GetMsgNeedSend.UpdatePhsSendErr(keyId);
}else{
GetMsgNeedSend.UpdatePhsSendSucc(keyId);
}
}
**/
if(phoneNum.contains(",")){ //多个号码 使用循环来发送
String[] sourceStrArray = phoneNum.split(",");
for (int i = 0; i < sourceStrArray.length; i++) {
String phnum=sourceStrArray[i];
Retmsg=SmgwClient.BL_SmsClient(sp,phnum,msgContent);
if(Retmsg.equals("发送成功")){
GetMsgNeedSend.UpdatePhsSendSucc(keyId,Retmsg);
}else{
GetMsgNeedSend.UpdatePhsSendErr(keyId,Retmsg);
}
}
}else{ //一个号码时不循环
Retmsg=SmgwClient.BL_SmsClient(sp,phoneNum,msgContent);
if(Retmsg.equals("发送成功") ){
GetMsgNeedSend.UpdatePhsSendSucc(keyId,Retmsg);
}else{
GetMsgNeedSend.UpdatePhsSendErr(keyId,Retmsg);
}
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
Retmsg="非常抱歉,有意料之外的问题,错误信息为:"+e.getMessage();
}
return Retmsg;
}
}
调用封装的连接短信网关的类
package com.ddd.client;
import java.io.UnsupportedEncodingException;
import com.ss.configuration.Config;
import com.ss.configuration.MsgConfigLoader;
import com.ss.entity.Phs_send;
import com.ss.smgp.Client;
import com.ss.smgpbean.Result;
import com.ss.smgpbean.Submit;
public class SmgwClient {
/**
* 发送短信
*/
public static String BL_SmsClient( String sp, String phoneNum, String msgContent) {
String returnValue="发送成功";
try {
String phsno =phoneNum;
//String phsno = "18111111111";
String tent =msgContent;
if(phsno == null)
{
System.out.println("手机号码长度错误( == null )!");
returnValue= "手机号码长度错误( == null )!";
}
/**if(!SmgwCheck.isValidLength(phsno, 1, 21)){
System.out.println("手机号码长度错误!");
return -1;
}
if(!SmgwCheck.isNumberString(phsno))
{
System.out.println("手机号码内容错误!");
return -1;
}
**/
if(tent.length() == 0)
{
System.out.println("短信内容为空!");
returnValue= "短信内容为空!";
}
byte[] content = tent.getBytes("iso-10646-ucs-2");
//System.out.println("content:"+content);
//System.out.println("content.length:"+content.length);
// 读取配置文件对象
// Config config = new Config();
//获取配置参数MsgConfigLoader.constantProperties.getProperty("ServerIP")
String ServerIP = MsgConfigLoader.constantProperties.getProperty("ServerIP");
String IcpId = MsgConfigLoader.constantProperties.getProperty("IcpId");
String IcpShareKey = MsgConfigLoader.constantProperties.getProperty("IcpShareKey");
//String SReplyPath = MsgConfigLoader.constantProperties.getProperty("SReplyPath");
String SReplyPath =sp;//2019-01-24 @pyx 修改从数据库自动获取相关SP号码,不在从配置文件获取
String ServerPort = MsgConfigLoader.constantProperties.getProperty("ServerPort");
String productid = MsgConfigLoader.constantProperties.getProperty("productid");
if(ServerIP == null)
{
System.out.println("读取配置错误!");
returnValue= "读取短信网关配置文件错误!";
}
if(!SmgwCheck.isIPAddressString(ServerIP))
{
System.out.println("短信网关IP地址格式错误!");
returnValue= "短信网关IP地址格式错误!";
}
String host = ServerIP;
if(!SmgwCheck.isValidLength(IcpId, 1, 15))
{
System.out.println("用户名长度错误!");
returnValue= "用户名长度错误!";
}
String account = IcpId;
String passwd = IcpShareKey;
if(!SmgwCheck.isValidLength(SReplyPath, 1, 22))
{
System.out.println("SP源号码长度错误!");
returnValue= "SP源号码长度错误!最大22";
}
if(!SmgwCheck.isNumberString(SReplyPath))
{
System.out.println("SP源号码内容错误!必须为数字");
returnValue= "SP源号码内容错误!必须为数字";
}
String spid = SReplyPath;
String spnum = SReplyPath;
if(ServerPort == null)
{
System.out.println("读取端口信息配置错误!");
returnValue= "读取端口信息配置错误!";
}
if(!SmgwCheck.isTCPPort(Integer.parseInt(ServerPort)))
{
System.out.println("短信网关端口格式错误!");
returnValue= "短信网关端口格式错误!";
}
int port = Integer.parseInt(ServerPort);
String productid1=productid;
//初始化client
Client client = new Client(host, port, 2,account, passwd,spid, 0);
//设置submit
Submit submit =new Submit();
submit.setSrcTermid(spnum);
submit.setDestTermid(phsno);
submit.setMsgContent(content);
submit.setMsgFormat(8);
if (productid1!=null) submit.setProductID(productid1);
//发送短信
if(content.length > 200){
Result[] result = client.SendLong(submit);
for (int i = 0; i < result.length; i++) {
/* System.out.println("--------------------------------");
System.out.println("Message "+i+"");
System.out.println("Status:" + result[i].ErrorCode);
System.out.println("MsgID:" + result[i].ErrorDescription);
System.out.println("--------------------------------");*/
if(result[i].ErrorCode != 0){
System.out.println("--------------------------------");
System.out.println("Message "+i+"");
System.out.println("Status:" + result[i].ErrorCode);
System.out.println("MsgID:" + result[i].ErrorDescription);
System.out.println("--------------------------------");
returnValue ="非常抱歉,短信发送失败,失败短信网关返回错误Status为:"+result[i].ErrorCode+",对应的错误信息为:"+GetReturnMsg(result[i].ErrorCode);
break;
}
}
}else{
Result result =client.Send(submit);
/* System.out.println("Status:"+result.ErrorCode);
System.out.println("MsgID:"+result.ErrorDescription);*/
if(result.ErrorCode != 0){
System.out.println("Status:"+result.ErrorCode);
System.out.println("MsgID:"+result.ErrorDescription);
returnValue ="非常抱歉,短信发送失败,短信网关返回错误Status为:"+result.ErrorCode+",对应的错误信息为:"+GetReturnMsg(result.ErrorCode);
}
}
//退出
client.Close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return returnValue;
}
/**
* 设置返回
*
* @param msgId 错误代码
* @return 错误名称
*/
private static String GetReturnMsg(int msgId){
String reMsg = "";
switch (msgId)
{
case 0:
reMsg = "成功";
break;
case 1:
reMsg = "系统忙(流控错误)";
break;
case 2:
reMsg = "超过最大连接数";
break;
case 3:
reMsg = "系统超时";
break;
case 4:
reMsg = "发送失败";
break;
case 10:
reMsg = "消息结构错误";
break;
case 11:
reMsg = "命令字错误";
break;
case 12:
reMsg = "序列号重复";
break;
case 20:
reMsg = "IP地址错误";
break;
case 21:
reMsg = "认证错误,登录密码错误";
break;
case 22:
reMsg = "版本错误,版本太高";
break;
case 30:
reMsg = "非法消息类型(SMType)";
break;
case 31:
reMsg = "非法优先级(Priority)";
break;
case 32:
reMsg = "非法资费类型(FeeType)";
break;
case 33:
reMsg = "非法资费代码(FeeCode)";
break;
case 34:
reMsg = "非法短消息格式(MsgFormat)";
break;
case 35:
reMsg = "非法时间格式";
break;
case 36:
reMsg = "非法短消息长度(MsgLength)";
break;
case 37:
reMsg = "有效期已过";
break;
case 38:
reMsg = "非法查询类别(QueryType)";
break;
case 39:
reMsg = "路由错误";
break;
case 40:
reMsg = "FixedFee错误,非法包月费/封顶费";
break;
case 41:
reMsg = "非法更新类型";
break;
case 42:
reMsg = "非法路由编号";
break;
case 43:
reMsg = "非法ServiceID";
break;
case 44:
reMsg = "非法ValidTime,有效期已经过期";
break;
case 45:
reMsg = "非法ATtime,定时发送时间已经过期";
break;
case 46:
reMsg = "非法源地址,源地址存在非法字符,或者源地址鉴权不通过";
break;
case 47:
reMsg = "非法目的地址";
break;
case 48:
reMsg = "非法计费地址";
break;
case 49:
reMsg = "非法CP代码";
break;
case 50:
reMsg = "非预付费用户";
break;
case 51:
reMsg = "余额不足";
break;
case 52:
reMsg = "非注册用户。属于预付费用户,但该号码还未被注册";
break;
case 53:
reMsg = "非注册SP";
break;
case 54:
reMsg = "帐号不可用";
break;
case 55:
reMsg = "扣费失败";
break;
case 56:
reMsg = "非法源网关代码";
break;
case 57:
reMsg = "非法查询号码";
break;
case 59:
reMsg = "非法SP类型";
break;
case 60:
reMsg = "非法上一条路由编号";
break;
case 61:
reMsg = "非法路由类型";
break;
case 62:
reMsg = "非法目标网关代码";
break;
case 63:
reMsg = "非法目标网关IP";
break;
case 64:
reMsg = "非法目标网关端口";
break;
case 65:
reMsg = "非法路由号码段";
break;
case 66:
reMsg = "非法终端所属省代码";
break;
case 67:
reMsg = "非法用户类型";
break;
case 68:
reMsg = "本节点不支持路由更新";
break;
case 69:
reMsg = "非法SP企业代码";
break;
case 70:
reMsg = "非法SP接入类型";
break;
case 71:
reMsg = "路由信息更新失败";
break;
case 72:
reMsg = "非法时间戳";
break;
case 73:
reMsg = "非法业务代码";
break;
case 74:
reMsg = "SP禁止下发时段";
break;
case 75:
reMsg = "SP发送超过日流量";
break;
case 76:
reMsg = "SP帐号过有效期";
break;
case 128:
reMsg = "预付费消息字段内容非法";
break;
case 129:
reMsg = "无效接口";
break;
case 130:
reMsg = "应答超时";
break;
case 131:
reMsg = "无权限";
break;
case 132:
reMsg = "不支持该消息";
break;
case 133:
reMsg = "禁止当前帐号发送短消息给网关";
break;
case 134:
reMsg = "禁止当前帐号从网关接收短消息";
break;
default:
reMsg = "未知错误";
break;
}
return reMsg;
}
}
Client方法
package com.ss.smgp;
import java.io.IOException;
import com.ss.smgpbean.Deliver;
import com.ss.smgpbean.Result;
import com.ss.smgpbean.Submit;
import com.ss.smgpbean.SubmitBatch;
import com.ss.smgpconnect.PConnect;
public class Client {
private PConnect pconnect;
private Result LoginResult;
public Client(String host, int port, int loginmode, String clientid,
String clientpasswd, String spid, int displaymode) {
this.pconnect = new PConnect(host, port, loginmode, clientid,
clientpasswd, spid, displaymode);
this.pconnect.start();
this.LoginResult = this.pconnect.Login();
if (this.LoginResult.ErrorCode != 0) {
this.pconnect.stop();
}
}
public Client(String host, int port, int loginmode, String clientid,
String clientpasswd, String spid) {
this.pconnect = new PConnect(host, port, loginmode, clientid,
clientpasswd, spid);
this.pconnect.start();
this.LoginResult = this.pconnect.Login();
if (this.LoginResult.ErrorCode != 0) {
this.pconnect.stop();
}
}
public void SetLogFile(String LogFile) throws IOException {
this.pconnect.SetLogFile(LogFile);
}
public void Close() {
this.pconnect.LogOut();
}
public void setDisplayMode(int displaymode) {
this.pconnect.setDisplayMode(displaymode);
}
public Result Send(Submit submit) {
if (this.LoginResult.ErrorCode == 0) {
return this.pconnect.Send(submit);
} else {
return this.LoginResult;
}
}
public Result[] SendLong(Submit submit) {
if (this.LoginResult.ErrorCode == 0) {
return this.pconnect.SendLong(submit);
} else {
Result [] result=new Result[1];
result[0]=this.LoginResult;
return result;
}
}
public void setLSmsOverTime(int second){
this.pconnect.setLSmsOverTime(second);
}
public Result SendBatch(SubmitBatch submit) {
if (this.LoginResult.ErrorCode == 0) {
return this.pconnect.SendBatch(submit);
} else {
return this.LoginResult;
}
}
public Result Login() {
return this.LoginResult;
}
public Deliver OnDeliver() {
if (this.LoginResult.ErrorCode == 0) {
return this.pconnect.OnDeliver();
} else {
return null;
}
}
public Deliver getDeliver() {
if (this.LoginResult.ErrorCode == 0) {
return this.pconnect.getDeliver();
} else {
return null;
}
}
//public set
}
PConnect 类
package com.ss.smgpconnect;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import com.dd.ClientUtil.Hex;
import com.dd.ClientUtil.TypeConvert;
import com.dd.smgpbean.Deliver;
import com.dd.smgpbean.LongDeliver;
import com.dd.smgpbean.Result;
import com.dd.smgpbean.Submit;
import com.dd.smgpbean.SubmitBatch;
import com.dd.smgpmessage.ActiveTestMessage;
import com.dd.smgpmessage.ActiveTestRespMessage;
import com.dd.smgpmessage.DeliverMessage;
import com.dd.smgpmessage.DeliverRespMessage;
import com.dd.smgpmessage.ExitMessage;
import com.dd.smgpmessage.LoginMessage;
import com.dd.smgpmessage.LoginRespMessage;
import com.dd.smgpmessage.Package;
import com.dd.smgpmessage.SubmitMessage;
import com.dd.smgpmessage.SubmitRespMessage;
import com.dd.smgppdu.WapPushPdu;
import com.dd.smgpprotocol.RequestId;
import com.dd.smgpprotocol.Tlv;
import com.dd.smgpprotocol.TlvId;
public class PConnect extends Thread {
/*
* parameter
*/
private String Host;
private int Port;
/*
* socket
*/
private Socket GwSocket;
private DataInputStream in;
private DataOutputStream out;
private boolean HasConnect=false;
/*
* smgp para
*/
private int LoginMode;
private String ClientID;
private String ClientPasswd;
private String SPID;
/*
* status
*/
private int DisplayMode = 1;
private int FirstLogin = 0;
private int HasLogin = 0;
private int Logout = 0;
/*
* 日志文件
*/
private FileWriter LogFile;
/*
* 临时数据存放变量
*/
private Package CurPack = new Package();
private Vector
private Vector deliverbuffer = new Vector();
private int SequenceId = 0;
private int SockTimeOut=60000;
public int getSockTimeOut() {
return SockTimeOut;
}
public void setSockTimeOut(int sockTimeOut) {
SockTimeOut = sockTimeOut;
}
/*
* 临时存放长短信
*/
private HashMap
private int LongSmsOverTime = 60;
public PConnect(String host, int port, int loginmode, String clientid,
String clientpasswd, String spid, int displaymode) {
this.Host = host;
this.Port = port;
this.LoginMode = loginmode;
this.ClientID = clientid;
this.ClientPasswd = clientpasswd;
this.SPID = spid;
this.DisplayMode = displaymode;
this.SequenceId = GetStartSeq();
this.HasConnect = this.Connect();
// this.Login();
}
public PConnect(String host, int port, int loginmode, String clientid,
String clientpasswd, String spid) {
this.Host = host;
this.Port = port;
this.LoginMode = loginmode;
this.ClientID = clientid;
this.ClientPasswd = clientpasswd;
this.SPID = spid;
this.SequenceId = GetStartSeq();
this.HasConnect = this.Connect();
// this.Login();
}
public void setDisplayMode(int displaymode) {
this.DisplayMode = displaymode;
}
public void SetLogFile(String LogFile) throws IOException {
this.LogFile = new FileWriter(LogFile);
}
private boolean Connect() {
try {
this.GwSocket = new Socket(this.Host, this.Port);
//if (this.GwSocket==null){System.out.println("can not create socket!");}
this.GwSocket.setSoTimeout(this.SockTimeOut);
//if (this.out==null){System.out.println("can not create socket!");}
this.in = new DataInputStream(this.GwSocket.getInputStream());
this.out = new DataOutputStream(this.GwSocket.getOutputStream());
this.FirstLogin++;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
if (this.FirstLogin > 0) {
try {
Thread.sleep(5000);
if (this.DisplayMode >= 2) {
System.out.println("Connect Fail!Reconneted");
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return this.Connect();
} else {
System.out.println(e);
return false;
}
}
return true;
}
private void ReConnect(int ms) {
if (this.Logout == 0) {
try {
Thread.sleep(ms);
System.out.println("Try Reconnect!");
this.Connect();
System.out.println("Try Login!");
// this.resume();
// Result result = this.Login();
LoginMessage lm = new LoginMessage(this.ClientID,
this.ClientPasswd, this.LoginMode);
SendBuf(lm.getBuf());
// out.write(lm.getBuf());
// System.out.println("ErrorCode:"+result.ErrorCode);
// System.out.println("ErrorDescription:"+result.ErrorDescription);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
do {
try {
int PackLen = in.readInt();
byte[] Message = new byte[PackLen - 4];
in.read(Message);
// 写日志
if (this.LogFile != null) {
this.LogFile.write("[" + GetTime() + "]" + "Recv:"
+ Hex.rhex(TypeConvert.int2byte((PackLen)))
+ Hex.rhex(Message) + "\n");
this.LogFile.flush();
}
// System.out.println("Recevice:"+Hex.rhex(Message));
this.CurPack = new Package(Message);
if (this.DisplayMode >= 2)
DisplayPackage(PackLen, Message, 0);
switch (this.CurPack.ReqestId) {
case 0x00000004: // ActiveTest
SendBuf((new ActiveTestRespMessage()).getBuf());
// out.write((new ActiveTestRespMessage()).getBuf());
if (this.DisplayMode >= 3) {
DisplayPackage((new ActiveTestRespMessage()).getBuf(),
1);
}
break;
case 0x00000003: // Deliver
DeliverMessage dm = new DeliverMessage(this.CurPack.Message);
DeliverRespMessage drm = new DeliverRespMessage(
dm.MsgID_BCD, dm.getSequence_Id(), 0);
SendBuf(drm.getBuf());
// out.write(drm.getBuf());
if (this.DisplayMode >= 2) {
DisplayPackage(drm.getBuf(), 1);
}
// 检查是否长短信
if (dm.TP_udhi == 1) {
// 长短信
AddLongSms(dm);
// System.out.println("收到长短信:" + dm.TP_udhi);
} else {
// 否
// System.out.println("收到putong短信" + dm.TP_udhi);
this.deliverbuffer.add(dm);
}
break;
case 0x80000001: // Login_Resp
break;
case 0x80000002: // Submit_Resp
break;
case 0x80000006: // Exit_Resp
break;
default:
break;
}
if (this.CurPack.ReqestId == RequestId.Deliver
|| this.CurPack.ReqestId == RequestId.Login_Resp
|| this.CurPack.ReqestId == RequestId.Submit_Resp
|| this.CurPack.ReqestId == RequestId.Exit_Resp
|| CheckLongSmsOverTime(this.LongSmsOverTime)) {
if (this.CurPack.ReqestId == RequestId.Submit_Resp
|| this.CurPack.ReqestId == RequestId.Login_Resp
|| this.CurPack.ReqestId == RequestId.Exit_Resp)
this.undoPack.add(this.CurPack);
synchronized (this) {
notify();
}
}
// if (CheckLongSmsOverTime(this.LongSmsOverTime)) notify();
} catch (SocketTimeoutException e) {
SendActive();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
if (this.DisplayMode >= 1 && this.Logout == 0) {
System.out.println("Lost Connect,ReConnect");
}
if (this.Logout == 0)
this.ReConnect(1000);
// this.resume();
continue;
}
} while (true);
}
public void setLSmsOverTime(int second) {
this.LongSmsOverTime = second;
}
private void SendActive(){
ActiveTestMessage activeTestMessage =new ActiveTestMessage();
try {
SendBuf(activeTestMessage.getBuf());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void AddLongSms(DeliverMessage dm) {
// int curstat=0;
if (this.longsmsbuffer.get(dm.SrcTermID) != null) {
int curstat = this.longsmsbuffer.get(dm.SrcTermID).AddDeliver(dm);
// 0表示正常
// 1表示长短信已经满了
// -1表示长短信出错了
if (curstat == 0) {
return;
} else if (curstat == 1) {
this.deliverbuffer.add(this.longsmsbuffer.get(dm.SrcTermID)
.MergeDeliver());
this.longsmsbuffer.remove(dm.SrcTermID);
} else if (curstat == -1) {
DeliverMessage[] tmpdeliver = this.longsmsbuffer.get(
dm.SrcTermID).popDeliver();
for (int i = 0; i < tmpdeliver.length; i++) {
this.deliverbuffer.add(tmpdeliver[i]);
}
this.longsmsbuffer.put(dm.SrcTermID, new LongDeliver(dm));
}
} else {
this.longsmsbuffer.put(dm.SrcTermID, new LongDeliver(dm));
}
return;
}
public synchronized Deliver OnDeliver() {
while (this.deliverbuffer.size() == 0) {
try {
synchronized (this) {
// System.out.println("Wait Deliver!");
wait();
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println("Size:"+this.deliverbuffer.size());
Deliver dm = new Deliver((DeliverMessage) (this.deliverbuffer.get(0)));
this.deliverbuffer.remove(0);
// System.out.println("Return Deliver");
return dm;
}
private boolean CheckLongSmsOverTime(int second) {
Iterator spit = this.longsmsbuffer.keySet().iterator();
// System.out.println("检查是否有长短信被执行");
while (spit.hasNext()) {
DeliverMessage[] tmpDeliverMsg;
String key = "";
if ((tmpDeliverMsg = this.longsmsbuffer.get(
(key = (String) spit.next())).CheckIfOverTime(second)) != null) {
for (int i = 0; i < tmpDeliverMsg.length; i++) {
this.deliverbuffer.add(tmpDeliverMsg[i]);
}
this.longsmsbuffer.remove(key);
return true;
}
}
return false;
}
public synchronized void LogOut() {
ExitMessage em = new ExitMessage();
this.Logout = 1;
try {
SendBuf(em.getBuf());
long sendTime = getTimeStamp();
Package tmppack = new Package();
while ((getTimeStamp() - sendTime) < 60000
&& ((tmppack = checkPackage(0, RequestId.Exit_Resp)) != null)) {
try {
synchronized (this) {
wait(60000);
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.GwSocket.close();
if (this.LogFile != null) {
this.LogFile.close();
}
this.stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized Deliver getDeliver() {
if (this.deliverbuffer.size() == 0) {
return null;
} else {
Deliver dm = new Deliver((DeliverMessage) (this.deliverbuffer
.get(0)));
this.deliverbuffer.remove(0);
// System.out.println("Return Deliver");
return dm;
}
}
public synchronized Result Login() {
if (this.HasConnect == false) {
return new Result(-2,"Can not creat socket!");
}
Result result = new Result();
try {
LoginMessage lm = new LoginMessage(this.ClientID,
this.ClientPasswd, this.LoginMode);
SendBuf(lm.getBuf());
// out.write(lm.getBuf());
while (this.CurPack == null
|| this.CurPack.ReqestId != RequestId.Login_Resp) {
try {
synchronized (this) {
wait();
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
LoginRespMessage lrm = new LoginRespMessage(this.CurPack.Message);
result.ErrorCode = lrm.getStatus();
result.ErrorDescription = "SerVersion:" + lrm.getServerVersion()
+ " ShareKey:" + Hex.rhex(lrm.getAuthenticatorServer());
if (lrm.getStatus() == 0)
this.HasLogin = 1;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized Result[] SendLong(Submit submit) {
Vector
Result[] result = new Result[splitContent.size()];
for (int i = 0; i < splitContent.size(); i++) {
Submit tmpSubmit = submit;
tmpSubmit.setMsgContent(addContentHeader(splitContent.get(i),
splitContent.size(), i + 1));
// System.out.println("msglen:"+tmpSubmit.getMsgLength());
//tmpSubmit.AddTlv(TlvId.TP_udhi, "1");
tmpSubmit.setTP_udhi(1);
tmpSubmit.AddTlv(TlvId.PkNumber, String.valueOf(i + 1));
tmpSubmit
.AddTlv(TlvId.PkTotal, String.valueOf(splitContent.size()));
result[i] = this.Send(tmpSubmit);
}
return result;
}
public synchronized Result SendWapPush(String desc, String url,
String srcTermId, String destTermid, String productID) {
Submit[] submitarray = WapPushPdu.getWapPushSubmit(desc, url,
srcTermId, destTermid, destTermid, productID);
Result result = null;
Result resulttmp = null;
for (int i = 0; i < submitarray.length; i++) {
resulttmp = this.Send(submitarray[i]);
// System.out.println(Hex.rhex(submitarray[i].getMsgContent()));
if (result == null || resulttmp.ErrorCode != 0) {
result = resulttmp;
}
}
return result;
}
public synchronized Result SendWapPush(String desc, String url,
Submit submit) {
Submit[] submitarray = WapPushPdu.getWapPushSubmit(desc, url, submit);
Result result = null;
Result resulttmp = null;
for (int i = 0; i < submitarray.length; i++) {
resulttmp = this.Send(submitarray[i]);
// System.out.println(Hex.rhex(submitarray[i].getMsgContent()));
if (result == null || resulttmp.ErrorCode != 0) {
result = resulttmp;
}
}
return result;
}
/*
* public synchronized Result SendWapPush(String disc, String url, String
* srcTermId, String destTermid, String productID) {
*
* Submit submit = new Submit(); try {
* submit.setMsgContent(getWapPushPdu(disc, url)); } catch
* (UnsupportedEncodingException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } submit.setMsgFormat(4);
* submit.AddTlv(TlvId.TP_udhi, "1"); submit.setDestTermid(destTermid);
* submit.setSrcTermid(srcTermId); submit.setProductID(productID);
* submit.setMsgType(7);
*
* System.out.println("msg len:" + submit.getMsgLength());
*
* return this.Send(submit); }
*/
/*
* private static byte[] getWapPushPdu(String disc, String url)
*
* throws UnsupportedEncodingException {
*
* byte[] WapPushDisc = disc.getBytes("UTF-8"); byte[] WapPushUrl =
* url.getBytes("UTF-8");
*
* byte WapPushHeader1[] = { 0x0B, // WAP PUSH 头部的总长度 // 长短信 0x00, //
* 标志这是个分拆短信 0x03, // 分拆数据元素的长度 0x03, // 长短信seq序号 0x01, // 总共1条 0x01, // 第1条
* // WAP PUSH 0x05, // WAP Push 0x04, // 分拆数据元素的长度 0x0B, // (byte) 0x84,//
* 0x23, // (byte) 0xF0 // }; byte WapPushHeader2[] = { 0x29, 0x06, 0x06,
* 0x03, (byte) 0xAE, (byte) 0x81, (byte) 0xEA, (byte) 0x8D, (byte) 0xCA };
* // WSP
*
* byte WapPushIndicator[] = { 0x02, // 标记位 0x05, // WAPFORUM//DTD SI
* 1.0//EN 0x6A, // UTF-8 0x00, // 标记开始 0x45, //
*
System.out.println("内容:" + Hex.rhex(submit.getMsgContent()));
return this.Send(submit);
}*/
/*
private static byte[] addFlashSmsHeader(byte[] content) {
// int curlong = content.length;
byte[] newcontent = new byte[content.length + 2];
newcontent[0] = 0x00;
newcontent[1] = 0x01;
System.arraycopy(content, 0, newcontent, 2, content.length);
return newcontent;
}
*/
private static byte[] addContentHeader(byte[] content, int total, int num) { // 为了加消息头参数为(原数据,总条数,当前条数)
// int curlong = content.length;
byte[] newcontent = new byte[content.length + 6];
newcontent[0] = 0x05;
newcontent[1] = 0x00;
newcontent[2] = 0x03;
newcontent[4] = (byte) total;
newcontent[5] = (byte) num;
System.arraycopy(content, 0, newcontent, 6, content.length);
return newcontent;
}
private static Vector
ByteArrayInputStream buf = new ByteArrayInputStream(content);
Vector
int msgCount = (int) (content.length / (140 - 6) + 1);
int LeftLen = content.length;
for (int i = 0; i < msgCount; i++) {
byte[] tmp = new byte[140 - 6];
if (LeftLen < (140 - 6))
tmp = new byte[LeftLen];
try {
buf.read(tmp);
tmpv.add(tmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LeftLen = LeftLen - tmp.length;
}
return tmpv;
}
public synchronized Result Send(Submit submit) {
/*
* if (submit.isLong()) { // 长短信 // submit.getMsgContent().length; }
* else { }
*/
if (submit.getMsgContent().length > 200) {
return (new Result(4, "Message too Long"));
}
Vector
if (this.SPID != null && !this.SPID.equals("")) {
tlv.add(new Tlv(TlvId.MsgSrc, this.SPID));
}
if (submit.getProductID() != null && !submit.getProductID().equals("")) {
tlv.add(new Tlv(TlvId.Mserviceid, submit.getProductID()));
}
if (submit.getTP_udhi()==1){
tlv.add(new Tlv(TlvId.TP_udhi,String.valueOf(1)));
}
if (submit.getLinkID() != null && !submit.getLinkID().equals("")) {
tlv.add(new Tlv(TlvId.LinkID, submit.getLinkID()));
}
if (submit.getOtherTlvArray() != null) {
for (int i = 0; i < submit.getOtherTlvArray().length; i++) {
tlv.add(submit.getOtherTlvArray()[i]);
}
}
Tlv[] tlvarray = new Tlv[tlv.size()];
// System.out.println("tlvlen:"+tlv.size());
for (int i = 0; i < tlv.size(); i++) {
// System.out.println(((Tlv)tlv.get(i)).Value);
tlvarray[i] = (Tlv) tlv.get(i);
}
String[] desttermidarray = new String[1];
desttermidarray[0] = submit.getDestTermid();
if (SequenceId++ == 0x7FFFFF) {
SequenceId = 0;
}
int tmpseq = SequenceId;
SubmitMessage sm = new SubmitMessage(submit.getMsgType(), submit
.getNeedReport(), submit.getPriority(), submit.getServiceID(),
submit.getFeetype(), submit.getFeeCode(), submit.getFixedFee(),
submit.getMsgFormat(), submit.getValidTime(), submit
.getAtTime(), submit.getSrcTermid(), submit
.getChargeTermid(), desttermidarray, submit
.getMsgLength(), submit.getMsgContent(), submit
.getReserve(), tlvarray, tmpseq);
try {
// System.out.println(Hex.rhex(sm.getBuf()));
SendBuf(sm.getBuf());
// out.write(sm.getBuf());
if (this.DisplayMode >= 2) {
DisplayPackage(sm.getBuf(), 1);
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return (new Result(-1, "Socket Error!"));
}
long sendTime = getTimeStamp();
/*
* while ((getTimeStamp() - sendTime) < 60000 && (this.CurPack == null
* || this.CurPack.ReqestId != RequestId.Submit_Resp ||
* this.CurPack.SequenceId != tmpseq)) {
*/
Package tmppack = new Package();
while ((getTimeStamp() - sendTime) < 60000
&& ((tmppack = checkPackage(tmpseq, RequestId.Submit_Resp)) == null)) {
// checkPackage(int, int)
try {
synchronized (this) {
wait(60000);
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (tmppack != null) {
SubmitRespMessage srm = new SubmitRespMessage(tmppack.Message);
return (new Result(srm.getStatus(), srm.getMsgID()));
} else {
System.out.println("SubmitResp超时!" + "Seq:" + tmpseq);
return (new Result(-1, "00000000000000000000"));
}
// if (srm==null) {
// return (new Result(-1,"Login Fail"));
// } else {
// }
}
private static Long getTimeStamp() {
return (new java.util.Date()).getTime();
}
public synchronized Result SendBatch(SubmitBatch submit) {
Vector tlv = new Vector();
if (this.SPID != null && !this.SPID.equals("")) {
tlv.add(new Tlv(TlvId.MsgSrc, this.SPID));
}
if (submit.getProductID() != null && !submit.getProductID().equals("")) {
tlv.add(new Tlv(TlvId.Mserviceid, submit.getProductID()));
}
if (submit.getLinkID() != null && !submit.getLinkID().equals("")) {
tlv.add(new Tlv(TlvId.LinkID, submit.getLinkID()));
}
if (submit.getOtherTlvArray() != null) {
for (int i = 0; i < submit.getOtherTlvArray().length; i++) {
tlv.add(submit.getOtherTlvArray()[i]);
}
}
Tlv[] tlvarray = new Tlv[tlv.size()];
// System.out.println("tlvlen:"+tlv.size());
for (int i = 0; i < tlv.size(); i++) {
// System.out.println(((Tlv)tlv.get(i)).Value);
tlvarray[i] = (Tlv) tlv.get(i);
}
// String[] desttermidarray = new String[1];
// desttermidarray[0] = submit.getDestTermid();
if (SequenceId++ == 0x7FFFFF) {
SequenceId = 0;
}
SubmitMessage sm = new SubmitMessage(submit.getMsgType(), submit
.getNeedReport(), submit.getPriority(), submit.getServiceID(),
submit.getFeetype(), submit.getFeeCode(), submit.getFixedFee(),
submit.getMsgFormat(), submit.getValidTime(), submit
.getAtTime(), submit.getSrcTermid(), submit
.getChargeTermid(), submit.getDestTermid(), submit
.getMsgLength(), submit.getMsgContent(), submit
.getReserve(), tlvarray, this.SequenceId);
try {
// System.out.println(Hex.rhex(sm.getBuf()));
SendBuf(sm.getBuf());
// out.write(sm.getBuf());
if (this.DisplayMode >= 2) {
DisplayPackage(sm.getBuf(), 1);
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return (new Result(-1, "Socket Error!"));
}
while (this.CurPack == null
|| this.CurPack.ReqestId != RequestId.Submit_Resp) {
try {
synchronized (this) {
wait();
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Result result = new Result();
SubmitRespMessage srm = new SubmitRespMessage(this.CurPack.Message);
// if (srm==null) {
// return (new Result(-1,"Login Fail"));
// } else {
return (new Result(srm.getStatus(), srm.getMsgID()));
// }
}
private void DisplayPackage(int len, byte[] message, int sendOrReceive) {
if (sendOrReceive == 0) {
System.out.println("-------------Receive Package-------------");
} else {
System.out.println("--------------Send Package--------------");
}
System.out.println("Length:" + len);
System.out.println("Pack:" + Hex.rhex(message));
}
private void DisplayPackage(byte[] message, int sendOrReceive) {
int len = TypeConvert.byte2int(message, 0);
byte[] messagetmp = new byte[message.length - 4];
// System.arraycopy(src, srcPos, dest, destPos, length)
System.arraycopy(message, 4, messagetmp, 0, messagetmp.length);
// System.out.println("message:"+Hex.rhex(message));
// System.out.println("messagetmp:"+Hex.rhex(messagetmp));
DisplayPackage(len, messagetmp, sendOrReceive);
}
private synchronized void SendBuf(byte[] buf) throws IOException {
this.out.write(buf);
if (this.LogFile != null) {
this.LogFile.write("[" + GetTime() + "]" + "Send:" + Hex.rhex(buf)
+ "\n");
this.LogFile.flush();
}
}
private Package checkPackage(int seq, int reqid) {
// System.out.println("PackNum:"+ this.undoPack.size());
for (int i = 0; i < this.undoPack.size(); i++) {
Package pk = (Package) this.undoPack.get(i);
if (pk.SequenceId == seq && pk.ReqestId == reqid) {
this.undoPack.remove(i);
return pk;
}
if (((new java.util.Date()).getTime() - pk.timestamp) > 60000) {
// 超时移除
this.undoPack.remove(i);
}
}
return null;
}
private static String GetTime() {
String TimeStamp = "";
Calendar now = Calendar.getInstance();
// now.getTime();
SimpleDateFormat bartDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return (bartDateFormat.format(now.getTime()));
/*
* TimeStamp =FormatInt(Integer.toString(now.YEAR)) +"年" +
* FormatInt(Integer.toString(now.MONTH + 1))+"月" +
* FormatInt(Integer.toString(now.DAY_OF_MONTH))+"日 " +
* FormatInt(Integer.toString(now.HOUR))+":" +
* FormatInt(Integer.toString(now.MINUTE ))+":" +
* FormatInt(Integer.toString(now.SECOND)); return TimeStamp;
*/
}
private static int GetStartSeq() {
SimpleDateFormat bartDateFormat = new SimpleDateFormat("HHmmss");
Calendar now = Calendar.getInstance();
// now.getTime();
return Integer.parseInt(bartDateFormat.format(now.getTime()));
}
}
好了,就贴这么多吧,其它还有很多,这个需要引包,主要的短信网关调用jar包可以去我上传的资源里面下载(https://download.csdn.net/download/puyoucai/10941130),本来想设置免费,但是不知道哪里整。