【发布时间】:2014-02-25 18:51:49
【问题描述】:
我正在使用串行端口通过 GSM/调制解调器发送短信。我的代码正在处理单个短信。当我尝试批量发送短信时出现问题。然后不发送短信,也不产生异常。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Windows.Forms;
namespace program.cs
{
public class Class1
{
public string[] strarray = new string[10];
SerialPort serialport1 = new SerialPort();
string com = "COM8";
int mybaudrate = 9600;
//this.strarray =System.IO.Ports.SerialPort.GetPortNames();
public void getports()
{
this.strarray = System.IO.Ports.SerialPort.GetPortNames();
}
public bool connetport()
{
bool Isopen;
serialport1.Close();
try
{
if (!this.serialport1.IsOpen)
{
this.serialport1.PortName = com;
this.serialport1.Open();
this.serialport1.BaudRate = mybaudrate;
this.serialport1.StopBits = System.IO.Ports.StopBits.One;
this.serialport1.Parity = System.IO.Ports.Parity.None;
this.serialport1.Handshake = System.IO.Ports.Handshake.None;
Isopen= serialport1.IsOpen;
}
Isopen = true;
}
catch (Exception ex)
{
Isopen = false;
throw ex;
}
return Isopen;
}
public void sendsms()
{
try
{
if (this.serialport1.IsOpen)
{
// to send bulk sms
serialport1.BaseStream.Flush();
int loop = 0;
int howmany = 0;
howmany = 200;
while (loop < howmany)
{
System.Threading.Thread.Sleep(3500);
string cb = char.ConvertFromUtf32(26);
this.serialport1.Write("AT+CMGF=1\r");
this.serialport1.Write("AT+CSCA=servicecenter\r
\n");//Ufone Service Center
this.serialport1.Write("AT+CMGS=\"" + "03468916446" + "\"\r\n");//
this.serialport1.Write("hello" + cb);//message text
message sending
System.Threading.Thread.Sleep(3500);
loop++;
}
MessageBox.Show("Message Sent Number" + loop);
serialport1.Close();
}
}
catch (Exception ex)
{
serialport1.Close();
throw ex;
}
}
}
}
上面的Class1是用来连接和发送短信的
主程序代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool check;
Class1 obj = new Class1();
private void button1_Click(object sender, EventArgs e)
{
check = obj.connetport();
MessageBox.Show("Connecton Status" + check);
obj.sendsms();
MessageBox.Show("have completed");
}
}
我在解决这个问题上投入了大量时间,但没有成功。您的帮助将不胜感激
【问题讨论】:
-
在使用前了解 Thread.Sleep 的作用。该循环将需要 23.3 分钟才能完成您现在的方式。还有你得到什么错误。也不要在连接端口的开头调用 serialport1.Close()。还可以处理您的命名和格式,例如 camelCase。
-
我没有收到任何错误,执行完成,没有任何错误或异常
-
我认为 Thread.sleep (暂停这些毫秒的进程)
-
如果将“howmany”设置为 1 并注释掉 //System.Threading.Thread.Sleep(3500);短信出去了吗?我同意 N00B.NET,那 3.5 秒的睡眠有问题。
-
还要检查您的串行端口设置。即确保奇偶校验位和停止位与调制解调器匹配。您还没有设置数据大小,它应该类似于 serialport1.DataBits = 8。
标签: c# serial-port