C#短信猫连接发送接收等代码[转]

本文提供了一个使用C#编程语言实现短信猫(SMS Modem)连接、发送及接收短信的完整示例代码。该代码包括串口配置、获取SIM卡信息、设置短信中心号码等功能,并展示了如何通过数据库记录短信的收发状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#短信猫连接发送接收等代码

C#编程 2009-11-11 16:22:06 阅读419 评论1   字号:   订阅

using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Drawing;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;

namespace ylModem.Modem
{
    public partial class ModemLink : UserControl
    {
        public ModemLink()
        {
            InitializeComponent();

            txtCenterNO.Text = System.Configuration.ConfigurationManager.AppSettings["CenterNo"];
        }

        public static int TotalNum = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["TotalNum"]);

        public static int UsedNum = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["UsedNum"]);

        public static int LastDay = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["LastDay"]);

        public static int LastHour = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["LastHour"]);

        public static string centerNO = "";

        public static ComPortClass.ComPortClass sp = null;

        public static bool loginStatus = false;

        private void btnConnect_Click(object sender, EventArgs e)
        {
            sp = new ComPortClass.ComPortClass(cmbPortName.Text.Trim(), Convert.ToInt32(cmbPortNum.Text));
            cmbPortName.Enabled = false;
            cmbPortNum.Enabled = false;
            btnConnect.Enabled = false;
            btnClose.Enabled = true;
            if (sp.sp.IsOpen)
            {
                loginStatus = true;
                this.rtbDisplay.Text = sp.SetMsgCenter(txtCenterNO.Text.Trim());
                centerNO = txtCenterNO.Text.Trim();
                sp.sp.DataReceived += new SerialDataReceivedEventHandler(ReceiveMessage);
            }
            else
            {
                rtbDisplay.Text = " 串口打开失败!";
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            sp.CloseCom();
            loginStatus = false;
            cmbPortName.Enabled = true;
            cmbPortNum.Enabled = true;
            btnConnect.Enabled = true;
            btnClose.Enabled = false;
        }

        private void btnCenterNO_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            if (loginStatus)
            {
                rtbDisplay.Text = sp.ATCommand("AT+CSCA?");
            }
            else
            {
                rtbDisplay.Text = "请先连接短信猫!";
            }
        }

        private void btnSIM_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            if (loginStatus)
            {
                rtbDisplay.Text = sp.ATCommand("AT+CCID");
            }
            else
            {
                rtbDisplay.Text = "请先连接短信猫!";
            }
        }

        private void btnSetCenterNo_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            if (loginStatus)
            {
                AppConfig config = new AppConfig();

                config.ConfigType = (int)ConfigFileType.AppConfig;

                config.SetValue("CenterNo", txtCenterNO.Text.Trim());

                centerNO = txtCenterNO.Text.Trim();

                rtbDisplay.Text = sp.ATCommand("AT+CSCA=" + txtCenterNO.Text.Trim() + ";&W");
            }
            else
            {
                rtbDisplay.Text = "请先连接短信猫!";
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            if (loginStatus)
            {
                rtbDisplay.Text = sp.ATCommand("AT+CSQ");
            }
            else
            {
                rtbDisplay.Text = "请先连接短信猫!";
            }
        }

        private void btnPhoneNum_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
            if (loginStatus)
            {
                rtbDisplay.Text = sp.ATCommand("AT+CNUM");
            }
            else
            {
                rtbDisplay.Text = "请先连接短信猫!";
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            rtbDisplay.Text = "";
        }

        private void ReceiveMessage(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(1000);
                string str = sp.ReadCom();
                Thread.Sleep(2000);
                str = str.Replace("/r/n", "").Replace(" ", "");
                if (str.Length > 6)
                {
                    if (str.Substring(0, 5) == "+CMTI")
                    {
                        int index = str.IndexOf(",");
                        string location = str.Substring(index + 1);
                        string value = sp.ReadMsg(location);
                        //MessageBox.Show(value, "有新短信", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        if (value.Substring(0, 3) == "内容:")
                        {
                            InsertReceive(value);
                        }
                        sp.ATCommand("AT+CMGD=" + location);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void InsertReceive(string pdu)
        {
            String sendmsg = pdu.Substring(pdu.IndexOf("内容:") + 3, pdu.IndexOf("---发送者:") - pdu.IndexOf("内容:") - 3);
            sendmsg = sendmsg.Replace("/0", "");
            String sendmobile = pdu.Substring(pdu.IndexOf("---发送者:") + 7, pdu.IndexOf("---接收时间:") - pdu.IndexOf("---发送者:") - 7);
            String receivetime = pdu.Substring(pdu.IndexOf("---接收时间:") + 8);

            OleDbConnection myConnection = new OleDbConnection(ylModem.main.DBConfig);
            myConnection.Open();

            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = new OleDbCommand("select phrase.receive from phrase,phrasegroup where phrasegroup.id=phrase.groupid and phrasegroup.status=1 and phrase.phrase='" + sendmsg.Trim() + "'", myConnection);
            DataSet ds = new DataSet();
            adapter.Fill(ds, "receive");

            if (ds.Tables["receive"].Rows.Count == 0)
            {
                OleDbCommand myCommand = myConnection.CreateCommand();
                OleDbTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);

                myCommand.Transaction = myTrans;
                myCommand.CommandText = "INSERT INTO receivemsg (sendmobile,sendmsg,receivetime,receivestatus) values ('" + sendmobile + "','" + sendmsg + "','" + receivetime + "','无回复')";
                myCommand.ExecuteNonQuery();
                myTrans.Commit();

                myCommand.Dispose();
                myTrans.Dispose();
            }
            else
            {
                String receiveStatus = InsertSend(sendmobile, (String)ds.Tables["receive"].Rows[0]["receive"]);

                OleDbCommand myCommand = myConnection.CreateCommand();
                OleDbTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);

                myCommand.Transaction = myTrans;
                myCommand.CommandText = "INSERT INTO receivemsg (sendmobile,sendmsg,receivetime,receivestatus) values ('" + sendmobile + "','" + sendmsg + "','" + receivetime + "','" + receiveStatus + "')";
                myCommand.ExecuteNonQuery();
                myTrans.Commit();

                myCommand.Dispose();
                myTrans.Dispose();
            }
            ds.Dispose();
            adapter.Dispose();
            myConnection.Close();
        }

        private string InsertSend(string sendMobile, string sendMsg)
        {
            if (LastDay != System.DateTime.Now.Day || LastHour != System.DateTime.Now.Hour)
            {
                UsedNum = 0;
                LastDay = System.DateTime.Now.Day;
                LastHour = System.DateTime.Now.Hour;
            }
            if (UsedNum < TotalNum)
            {
                string sendresult = sp.SendToCom(sendMobile.Trim(), centerNO.Trim(), sendMsg.Trim());

                if (sendresult.Contains("OK"))
                {
                    UsedNum++;
                    OleDbConnection myConnection = new OleDbConnection(ylModem.main.DBConfig);
                    myConnection.Open();
                    OleDbCommand myCommand = myConnection.CreateCommand();
                    OleDbTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);

                    myCommand.Transaction = myTrans;
                    myCommand.CommandText = "INSERT INTO sendreport (sendmobile,sendmsg,sendstatus) values ('" + sendMobile + "','" + sendMsg + "','发送成功')";
                    myCommand.ExecuteNonQuery();
                    myTrans.Commit();

                    myCommand.Dispose();
                    myTrans.Dispose();
                    myConnection.Close();

                    return "回复成功";
                }
                else
                {
                    OleDbConnection myConnection = new OleDbConnection(ylModem.main.DBConfig);
                    myConnection.Open();
                    OleDbCommand myCommand = myConnection.CreateCommand();
                    OleDbTransaction myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);

                    myCommand.Transaction = myTrans;
                    myCommand.CommandText = "INSERT INTO sendreport (sendmobile,sendmsg,sendstatus) values ('" + sendMobile + "','" + sendMsg + "','发送失败')";
                    myCommand.ExecuteNonQuery();
                    myTrans.Commit();

                    myCommand.Dispose();
                    myTrans.Dispose();
                    myConnection.Close();

                    return "回复失败";
                }
            }
            else
            {
                return "未回复";
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值