首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 開發 Windows 服務發送中文簡訊:Oxygen SMS 控制項與定時輪詢架構

     編輯:關於C#

專案需求

  • 企業內部多系統(網頁、Outlook、非 Windows 主機)需發送簡訊
  • 統一透過 Windows Service 背景服務處理
  • 客戶端僅需寫入文字檔到指定資料夾
  • 硬體:Nokia 3210 + 序列傳輸線 (COM1)

架構設計


[客戶端系統] ──寫入 .sms 檔──▶ [共享資料夾 F:\Sms\Data\FileToSend]
                                                    │
                                                    ▼
                                          [Windows Service: SmsServer]
                                          ├─ Timer 定時輪詢 (每 30 秒)
                                          ├─ 讀取 .sms 檔 (GB2312 編碼)
                                          ├─ Oxygen SMS ActiveX 發送
                                          ├─ 成功 → 移至 HadBeenSend 備份
                                          └─ 失敗 → 記錄 EventLog

專案建立與參考

  1. Visual Studio → 新增專案 → Windows Service → 命名 SmsServer
  2. 服務設計介面:設定 ServiceName = "SmsServer"
  3. 工具箱拖入:Timer (System.Timers)、EventLog
  4. 加入參考 → COM → Oxygen SMS ActiveX Control (SMSControl.ocx)

核心程式碼實作


using System;
using System.IO;
using System.Text;
using System.Timers;
using System.Diagnostics;
using System.ServiceProcess;
using O2SMSXControl; // Oxygen 命名空間

namespace SmsServer
{
    public partial class SmsServer : ServiceBase
    {
        private Timer _timer;
        private EventLog _eventLog;
        private O2SMSX _sms;

        public SmsServer()
        {
            InitializeComponent();
            _timer = new Timer(30000) { AutoReset = true };
            _timer.Elapsed += Timer_Elapsed;
            _eventLog = new EventLog { Source = "SmsServer" };
        }

        protected override void OnStart(string[] args)
        {
            _sms = new O2SMSXClass();
            _sms.ConnectionMode = 0;           // 0 = Cable
            _sms.ComNumber = 1;                // COM1
            _sms.Model = 0;                    // 0 = Nokia 3210
            _sms.Open();
            _sms.SetSMSCNumber("+8613800754500"); // 簡訊中心號碼 (依地區調整)
            _timer.Start();
            _eventLog.WriteEntry("簡訊服務已啟動");
        }

        protected override void OnStop()
        {
            _timer.Stop();
            _sms?.Close();
            _eventLog.WriteEntry("簡訊服務已停止");
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop(); // 防止重入
            try
            {
                var dir = new DirectoryInfo(@"F:\Sms\Data\FileToSend");
                foreach (var file in dir.GetFiles("*.sms"))
                {
                    try
                    {
                        string id, phone, text;
                        using (var fs = file.OpenRead())
                        using (var sr = new StreamReader(fs, Encoding.GetEncoding("GB2312")))
                        {
                            id = Path.GetFileNameWithoutExtension(file.Name);
                            phone = sr.ReadLine()?.Trim();
                            text = sr.ReadToEnd()?.Trim();
                        }

                        if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(text)) continue;
                        if (phone.Length > 11) phone = phone.Substring(0, 11);
                        if (text.Length > 50) text = text.Substring(0, 50);

                        // 發送 Unicode 簡訊 (支援中文)
                        _sms.SendUnicodeSMSMessage(phone, text, 6, false, "");

                        // 備份並刪除
                        file.CopyTo($@"F:\Sms\Data\HadBeenSend\{file.Name}", true);
                        file.Delete();
                    }
                    catch (Exception ex)
                    {
                        _eventLog.WriteEntry($"處理 {file.Name} 失敗:{ex.Message}", EventLogEntryType.Error);
                    }
                }
            }
            finally
            {
                _timer.Start();
            }
        }
    }
}

安裝與部署

  1. 建置專案產生 SmsServer.exe
  2. 開啟 Developer Command Prompt (管理員):
    installutil SmsServer.exe
    
  3. 服務管理工具 (services.msc) 中找到 SmsServer,設定啟動類型為「自動」,啟動服務
  4. 建立資料夾結構:
    
    F:\Sms\Data\FileToSend     (投遞區)
    F:\Sms\Data\HadBeenSend    (備份區)
    

客戶端投遞範例 (.sms 檔案格式)


// 檔名:20240115001.sms
0912345678
親愛的用戶,您的驗證碼是 123456,請於 5 分鐘內輸入。

第一行:手機號碼;第二行起:簡訊內容 (GB2312 編碼)。

關鍵技術細節

擴充建議

  • 支援多 COM 埠 / 多手機負載平衡
  • 資料庫記錄發送狀態、失敗重試機制
  • 提供 WCF / Web API 介面取代檔案投遞
  • 升級為 .NET 6+ Windows Service (Generic Host)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
項目說明
編碼Encoding.GetEncoding("GB2312") 讀取檔案;SendUnicodeSMSMessage 發送 Unicode (UCS2) 簡訊,支援中文
簡訊中心號碼必須正確設定 SetSMSCNumber,否則發送失敗 (各地門號不同,如中華電信 +8613800754500)
錯誤處理Try-Catch 包裹單一檔案處理,失敗寫入 EventLog,不中斷整批處理
計時器重入防護_timer.Stop() 在處理開始,finally 重新啟動
權限服務以 LocalSystem 執行,需確保 COM 埠存取權限、資料夾讀寫權限