我已经开发了使用C#的GSMCOMM库发送短信的ac#应用程序。但是我面对的问题是,当我尝试使用gsmcomm objects.send消息方法发送消息时。有时它会给出异常该手机未连接,有时它会使异常端口无法打开。 我在下面分享我的代码: 用于将pc连接到手机gsm调制解调器的代码。有时它会发送消息而不给出任何例外 将手机连接到电脑的代码。
private bool ConnectPhone()
{
string conectionStr = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
clsFileLogger.VerifyLogFileDirectory();
clsFileLogger.WriteToLog("DB Connection: " + conectionStr);
conn = new SqlConnection(@conectionStr);
int port = Convert.ToInt32(ConfigurationSettings.AppSettings["port"]);
int baudRate = Convert.ToInt32(ConfigurationSettings.AppSettings["baudRate"]);
int timeout = Convert.ToInt32(ConfigurationSettings.AppSettings["timeout"]);
gsmComm = new GsmCommMain(port, baudRate, timeout);
try
{
Isconnected = false;
if (gsmComm.IsConnected() == false)
{
gsmComm.Open();
}
Isconnected = gsmComm.IsConnected();
clsFileLogger.WriteToLog("\nConnected with GSM Modam");
}
catch (Exception)
{
clsFileLogger.WriteToLog("\nUnable to open the port.");
}
return Isconnected;
}
和发送短信的代码
if (gsmComm.IsConnected() == false)
{
this.ConnectPhone();
}
pdu = new SmsSubmitPdu(strSMS, cellNO, "");
gsmComm.SendMessage(pdu);
catch (Exception ex)
{
throw ex;
}
答案 0 :(得分:4)
当你使用gsmcomm时...首先,在comboBox中列出你的comPorts 我是vb.net专家..你可以阅读这段代码并将其翻译成C# 1)在表单和form_load中创建一个组合框,编写此代码
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each prt In My.Computer.Ports.SerialPortNames
comboBox1.Items.Add(prt)
Next
End Sub
在您的全球范围内,编写此代码
Public Property mymodem As GsmCommMain
在项目中添加一个子项,如下所示
Private Sub connect()
Try
Cursor.Current = Cursors.WaitCursor
If comboBox1.Text = "" Then Return
If IsNothing(mymodem) Then mymodem = New GsmCommMain(comboBox1.Text)
If Not mymodem.IsOpen Then mymodem.Open()
Cursor.Current = Cursors.Default
Catch ex As Exception
richTextBox1.AppendText(ex.Message & vbCrLf) 'i add a richtextbox to my form for show exceptions and my produced declaration
End Try
End Sub
之后放了一个手机号码的文本框..将其命名为txttel 还为textMessage设置了一个文本框..将其命名为txtMSG 按下按钮发送消息..将其命名为btnsend 剩下的代码将是这样的..
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If String.IsNullOrEmpty(txtMSG.Text.Trim) Then Return
SendSMS()
End Sub
Private Sub SendSMS()
Try
If Not mymodem.IsOpen Then connect()
Dim pdu As New SmsSubmitPdu(txtMSG.Text.Trim & vbCr, txtTel.Text)
mymodem.SendMessage(pdu)
richTextBox1.AppendText("your message sent successfully")
Catch ex As Exception
richTextBox1.AppendText(ex.Message)
End Try
End Sub
最后一定要关闭你的端口..像这样
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If Not IsNothing(mymodem) AndAlso mymodem.IsOpen Then
mymodem.Close()
End If
End Sub
答案 1 :(得分:1)
试试这些指南(对我有帮助): http://www.codeproject.com/Articles/325731/Bulk-SMS-Sender http://www.codeproject.com/Articles/20420/How-To-Send-and-Receive-SMS-using-GSM-Modem
但似乎您的com-port打开问题不在您的代码中。尝试使用Teraterm应用程序测试您的端口。当你开始运行你的应用程序时,确保端口没有打开(它可能在上次启动后仍然打开)。