[客戶端系統] ──寫入 .sms 檔──▶ [共享資料夾 F:\Sms\Data\FileToSend]
│
▼
[Windows Service: SmsServer]
├─ Timer 定時輪詢 (每 30 秒)
├─ 讀取 .sms 檔 (GB2312 編碼)
├─ Oxygen SMS ActiveX 發送
├─ 成功 → 移至 HadBeenSend 備份
└─ 失敗 → 記錄 EventLog
SmsServerServiceName = "SmsServer"Timer (System.Timers)、EventLog
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();
}
}
}
}
SmsServer.exeinstallutil SmsServer.exe
services.msc) 中找到 SmsServer,設定啟動類型為「自動」,啟動服務
F:\Sms\Data\FileToSend (投遞區)
F:\Sms\Data\HadBeenSend (備份區)
// 檔名:20240115001.sms
0912345678
親愛的用戶,您的驗證碼是 123456,請於 5 分鐘內輸入。
第一行:手機號碼;第二行起:簡訊內容 (GB2312 編碼)。
| 項目 | 說明 |
|---|---|
| 編碼 | Encoding.GetEncoding("GB2312") 讀取檔案;SendUnicodeSMSMessage 發送 Unicode (UCS2) 簡訊,支援中文 |
| 簡訊中心號碼 | 必須正確設定 SetSMSCNumber,否則發送失敗 (各地門號不同,如中華電信 +8613800754500) |
| 錯誤處理 | Try-Catch 包裹單一檔案處理,失敗寫入 EventLog,不中斷整批處理 |
| 計時器重入防護 | _timer.Stop() 在處理開始,finally 重新啟動 |
| 權限 | 服務以 LocalSystem 執行,需確保 COM 埠存取權限、資料夾讀寫權限 |