废话不多说,直接上代码!
public class EmppService : System.Web.Services.WebService
{
#region 私有变量
/// <summary>
/// 短信列表
/// </summary>
private static List<string[]> list = new List<string[]>();
private static object lockObject = new object();
private static ILog _log = LogManager.GetLogger("EmppService");
#endregion
#region 构造函数
static EmppService()
{
//初始化log配置信息
FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config");
log4net.Config.XmlConfigurator.Configure(file);
//开启发送短信线程
Thread t1 = new Thread(Send);
t1.Start();
}
#endregion
private static void Send()
{
//轮询 短信列表
while (true)
{
try
{
if (list.Count > 0)
{
DateTime beginTime = DateTime.Now;
string mobile = string.Empty;
string content = string.Empty;
lock (lockObject)
{
mobile = list[0][0];
content = list[0][1];
//移除当前内容
list.RemoveAt(0);
}
_log.InfoFormat("开始发送短信,mobile:{0},content:{1}", mobile, content);
//初始化com组件
emptcl empp = new emptclClass();
//注册 提交短信发送状态事件
empp.SubmitRespInterface += SubmitRespInterface;
//连接短信发送服务器
ConnectResultEnum result = empp.connect(WebConfig.Host, WebConfig.Port, WebConfig.AccountId, WebConfig.Password);
if (empp == null || !empp.connected)
{
_log.Error("Empp服务连接失败!");
return;
}
//创建短消息
ShortMessage shortMsg = new ShortMessageClass();
shortMsg.srcID = WebConfig.AccountId; //获取发送短信者ID
shortMsg.needStatus = true; //获取是否返回状态报告标志
//初始化 信息接收人
Mobiles mob = new MobilesClass();
mob.Add(mobile);
shortMsg.DestMobiles = mob; //发送的手机号
shortMsg.content = content; //短信内容
shortMsg.SendNow = true; //设置是否立即发送短信标志
//发送短信
empp.submit(shortMsg);
//断开empp
empp.disconnect();
TimeSpan ts = DateTime.Now - beginTime;
_log.InfoFormat("发送短信结束,时间:{0}", ts.ToString());
}
}
catch (Exception ex)
{
_log.Error("发生异常!", ex);
}
Thread.Sleep(3000);
}
}
/// <summary>
/// 接收服务器返回的发送状态
/// </summary>
/// <param name="sm"></param>
static void SubmitRespInterface(SubmitResp sm)
{
if (sm.Result != 0)
{//发送失败 则记录错误消息
_log.WarnFormat("传真发送失败,Result:{0},MsgId:{1}", sm.Result.ToString(), sm.MsgID);
}
}
#region WebMethod
[WebMethod]
public void SendSingleMessage(string mobile, string content)
{
lock (lockObject)
{
//添加到短信列表中
list.Add(new string[] { mobile, content });
}
_log.InfoFormat("接收到短信申请,mobile:{0},content:{1}", mobile, content);
}
#endregion
}