Click here to Skip to main content
Email Password   helpLost your password?
Screenshot - MainScreen.jpg

Introduction

SMS client and server is an application software which is used for sending and receiving messages(SMS). It listens for incoming messages to arrive, processes the message if it's in a valid format. Note the processing of arrived messages depends on the application which will be discussed later. I am going to explain the following things:

  1. Communication Port Settings
  2. Receive Incoming Message
  3. Send Messages
  4. Read All Messages (Sent by the users)
  5. Delete Messages (One or All)

I have used the GSMComm Library for Sending and Receiving SMS. You require a GSM modem or phone for sending an SMS.

Using the code

1) Communication Port Settings

Screenshot - CommSettings.jpg

CommSetting class is used for storing comm port settings:

public class CommSetting
{
    public static int Comm_Port=0;
    public static Int64 Comm_BaudRate=0;
    public static Int64 Comm_TimeOut=0;
    public static GsmCommMain comm;

    public CommSetting()
    {
        //

        // TODO: Add constructor logic here

        //

    }
}

Comm is an object of type GsmCommMain which is required for sending and receiving messages. We have to set the Comm port, Baud rate and time out for our comm object of type GsmCommMain. Then try to open with the above settings. We can test the Comm port settings by clicking on the Test button after selecting the Comm port, baud rate and Time out. Sometimes if the comm port is unable to open, you will get a message "No phone connected". This is mainly due to Baud rate settings. Change the baud rate and check again by clicking the Test button until you get a message "Successfully connected to the phone."

Before creating a GSMComm object with settings, we need to validate the port number, baud rate and Timeout.

The EnterNewSettings() does validation, returns true if valid, and will invoke SetData(port,baud,timeout) for comm setting.

The following block of code will try to connect. If any problem occurs "Phone not connected" message appears and you can either retry by clicking on the Retry button or else Cancel.

GsmCommMain comm = new GsmCommMain(port, baudRate, timeout);
try
{
        comm.Open();
        while (!comm.IsConnected())
        {
            Cursor.Current = Cursors.Default;
            if (MessageBox.Show(this, "No phone connected.",
               "Connection setup", MessageBoxButtons.RetryCancel,
                 MessageBoxIcon.Exclamation) == DialogResult.Cancel)
            {
                comm.Close();
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
        }

        // Close Comm port connection (Since it's just for testing

        // connection)

        comm.Close();
}
catch(Exception ex)
{
    MessageBox.Show(this, "Connection error: " + ex.Message,
    "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

// display message if connection is a success.

MessageBox.Show(this, "Successfully connected to the phone.",
"Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
Screenshot - SucessfullyConnected.jpg

2) Receive Incoming Message

We are going to register the following events for GSMComm object comm.

  1. PhoneConnected
    This event is invoked when you try to open the Comm port. The event handler for Phone connected is comm_PhoneConnected which will invoke OnPhoneConnectionChange(bool connected) with the help of Delegate ConnectedHandler.
  2. MessageReceived
    This event is invoked when a message arrives at the GSM phone. We will register with MessageReceivedEventHandler. When the incoming message arrives, the comm_MessageReceived method will be invoked which in turn calls the MessageReceived() method in order to process the unread message. GSMComm object comm has a method ReadMessages which will be used for reading messages. It accepts the following parameters phone status (All, ReceivedRead, ReceivedUnread, StoredSent, and StoredUnsent) and storage type: SIM memory or Phone memory.
private void MessageReceived()
{
    Cursor.Current = Cursors.WaitCursor;
    string storage = GetMessageStorage();
    DecodedShortMessage[] messages = CommSetting.comm.ReadMessages
                   (PhoneMessageStatus.ReceivedUnread, storage);
    foreach(DecodedShortMessage message in messages)
    {
         Output(string.Format("Message status = {0},
     Location =  {1}/{2}",
         StatusToString(message.Status),
         message.Storage, message.Index));
         ShowMessage(message.Data);
         Output("");
    }

    Output(string.Format("{0,9} messages read.",
                messages.Length.ToString()));
    Output("");
}   

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message.

3) Send Message

Screenshot - SendSMS.jpg

You can send an SMS by keying in the destination phone number and text message.

If you want to send a message in your native language (Unicode), you need to check in Send as Unicode(UCS2). GSMComm object comm has a SendMessage method which will be used for sending SMS to any phone. Create a PDU for sending messages. We can create a PDU in straight forward version as:

SmsSubmitPdu pdu = new SmsSubmitPdu
        (txt_message.Text,txt_destination_numbers.Text,"");

An extended version of PDU is used when you are sending a message in Unicode.

 try
{
    // Send an SMS message

    SmsSubmitPdu pdu;
    bool alert = chkAlert.Checked;
    bool unicode = chkUnicode.Checked;

    if (!alert && !unicode)
    {
        // The straightforward version

        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text,"");
    }
    else
    {
        // The extended version with dcs

        byte dcs;
        if (!alert && unicode)
            dcs = DataCodingScheme.NoClass_16Bit;
        else
        if (alert && !unicode)
            dcs = DataCodingScheme.Class0_7Bit;
        else
        if (alert && unicode)
            dcs = DataCodingScheme.Class0_16Bit;
        else
            dcs = DataCodingScheme.NoClass_7Bit;

        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text, "", dcs);
    }

    // Send the same message multiple times if this is set

        int times = chkMultipleTimes.Checked ?
                int.Parse(txtSendTimes.Text) : 1;

    // Send the message the specified number of times

    for (int i=0;i<times;i++)
    {
        CommSetting.comm.SendMessage(pdu);
        Output("Message {0} of {1} sent.", i+1, times);
        Output("");
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Cursor.Current = Cursors.Default;

4) Read All Messages

Screenshot - ReadAllMessages.jpg

You can read all messages from the phone memory of SIM memory. Just click on "Read All Messages" button. The message details such as sender, date-time, text message will be displayed on the Data Grid. Create a new row for each read message, add to Data table and assign the Data table to datagrid's source

private void BindGrid(SmsPdu pdu)
{
    DataRow dr=dt.NewRow();
    SmsDeliverPdu data = (SmsDeliverPdu)pdu;

    dr[0]=data.OriginatingAddress.ToString();
    dr[1]=data.SCTimestamp.ToString();
    dr[2]=data.UserDataText;
    dt.Rows.Add(dr);

    dataGrid1.DataSource=dt;
}

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message. The only change in processing Received message and Read message is the first parameter.

For received message

DecodedShortMessage[] messages =
  CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);

For read all messages

DecodedShortMessage[] messages =
   CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage);

5) Delete Messages (One or All)

Screenshot - DeleteMessage.jpg

All messages which are sent by the users will be stored in SIM memory and we are going to display them in the Data grid. We can delete a single message by specifying the message index number. We can delete all messages from SIM memory by clicking on "Delete All" button. Messages are deleted based on the index. Every message will be stored in memory with a unique index.

The following code will delete a message based on index:

// Delete the message with the specified index from storage

CommSetting.comm.DeleteMessage(index, storage);

To delete all messages from memory( SIM/Phone)

// Delete all messages from phone memory

CommSetting.comm.DeleteMessages(DeleteScope.All, storage); 

The DeleteScope is an Enum which contains:

  1. All
  2. Read
  3. ReadAndSent
  4. ReadSentAndUnsent

Applications

Here are some interesting applications where you can use and modify this software.

1) Pre paid Electricity

Scenario (Customer)

The customer has agreed for pre paid electricity recharges with the help of recharge coupons. The coupon is made available at shops. The customer will first buy the coupons from shops; every coupon consists of Coupon PIN which will be masked, the customer needs to scratch to view the PIN number. The customer will send an SMS to the SMS Server with a specified message format for recharging.

Message Format for Recharging:
RECHARGE <Coupon No> <Customer ID>

Scenario (Server Database)

On the Server, the Database consists of Customer information along with his telephone number, there will a field named Amount which will be used and updated when the customer recharged with some amount. This application becomes somewhat complex, an automatic meter reading software along with hardware needs to be integrated with this. Automatic meter reading systems will read all meter readings and calculate the amount to be deducted for the customer.

2) Astrology

You can implement as astrology software. The user will send an SMS with his zodiac sign. The SMS server will maintain an Astrology Database with zodiac sign and a text description which contains a message for the day. The Database is required to be updated daily for all zodiac signs.

Message Format which will be used by the user to get message of the day:
Zodiac Sign

3) Remote Controlling System

We can implement a remote controlling system, for example you need to:

  1. Shutdown
  2. Restart
  3. Log off system

You can send an SMS. The SMS server will listen and then process the message. Based on the message format sent by the user we can take action.
Example if message format is:
SHUTDOWN
Send to SMS phone number.

Conclusion

This project wouldn't be completed unless I thank the GSMComm Lib developer "Stefan Mayr". I customized my application using this Library. You can download the sample project, library from the web link which I provided under the Reference section.

Reference

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHow to send more than 160 charachters
Muhammad Adnan Umar
19hrs 36mins ago 
Please tell me how can i send more than 160 characters in SMS.
this limited to only 160 chars. but i want to send more than 160.
thanx
aaa

GeneralRe: How to send more than 160 charachters
kingkhan789
14hrs 6mins ago 
Salam Muhammad Adnan,
U have to use another library as well.I m pasting my code here.so follow it.it is working correctly.


// Code

using SMSPDULib;
if (replymessage.Length > 160)
{
string[] finalMessage = getFinalMessage(replymessage,data.OriginatingAddress);
SendMultiple(finalMessage);// Calling SendMultiple Function
}


// get Final Message
public string[] getFinalMessage(string message,string cellNo)
{
string[] sms_pdu_array= new string[255];
try
{
// Compose Long Message and Encode it
SMS sms = new SMS();
sms.Message = message;
sms.PhoneNumber = cellNo;
sms.Direction = SMSDirection.Submited;
sms_pdu_array = sms.ComposeLongSMS(SMS.SMSEncoding._7bit);
}
catch (Exception ex)
{
Output(ex.Message);
}


return sms_pdu_array;
}

// Send Multiparts of a Message
private void SendMultiple(string[] pdus)
{
SmsSubmitPdu autoReply = null;
bool includeSmsC = true;
Cursor.Current = Cursors.WaitCursor;
try
{
// Send the created messages
foreach (string pdu in pdus)
{
int len = pdu.Length;
autoReply = new SmsSubmitPdu(pdu, includeSmsC, len);
CommSetting.comm.SendMessage(autoReply);
}

}
catch (Exception ex)
{
ShowException(ex);
}

Cursor.Current = Cursors.Default;
}
GeneralGreat work dude.
maulik.shah88
21:29 5 Mar '10  
Thumbs Up You explained great
GeneralRe: Great work dude.
Ranjan.D
3:25 10 Mar '10  
Thank You!
Ranjan.D

GeneralI need ur help
samata kawankar
19:35 28 Feb '10  
U r brilliant. This project is working properly i need little bit of help frm u, i want to know how do i implememnt this project in asp.net page bcoz i am currently developing a website which include social networking facilities and sms facility pls help me out
GeneralBadly need help to send sms
Najmul Hoda
21:03 25 Feb '10  
Hi Ranjan.......
I must thank u for writting such a great article.
I have been using your code since Jun 09 for receiving sms. And every day I receive approx 7-8 thousand sms using your code.

Now I have requirment to send sms but whenever I am trying to send, I am getting an exception "Message service error 500". I am using Micromax MMX 372G 3G USB Modem. I searched on the net for resolving this problem but did not get any right solution that would work for me.

Can you please help me. I need the solution badly.

Thanks,
Najmul
Najmul Hoda

I want to be programmer till death.

GeneralRe: Badly need help to send sms
Ranjan.D
18:10 26 Feb '10  
Hi Najmul,

Thank you for using code to Send SMS. First of all did you tried sending SMS using Windows -> Hyperterminal?
Try with that and know the Timeout which you can send. There shouldn't be any problem to send SMS. Also try debugging the project. Please explain the steps you have taken and the approach you have worked on because even its very difficult for me to know understand with this error message 'Message service error 500'.
Are you trying to send SMS when you are receiving SMS ???
Ranjan.D

GeneralProblem While Reading Data from Phone
UmakantGoyal
23:12 17 Feb '10  
Hi All,

I am able to send sms using given application. But whenever i tried to perform read operation (try to read SMS, try to get SMSC Address and Operator Info) on my phone using given code, i encountered an error "No data Received from phone after waiting for 30047 ms".
I have tried to connect with my using different baud rate and different timeout value. But nothing worked for me. Every time i got same error.

Please let me know the reason for the same.
I am having samsung E250 phone.

Thanks in Advance
Generalfire SMSReceived event
Ehsan.gis
0:58 10 Feb '10  
Hi Ranjan,
thanks for great piece of programme.
I am using your GsmCommMain for my SMS based project,but it does not fire
SMSReceived event.
I am working on C#.Net

Thanks
GeneralSend Business Cards
Zeeshan Saeed
20:48 31 Jan '10  
How can we send business cards with this application ???
Generalhi Using AT program to send SMS messages in vb6 for sony ericsson
kourosh modi
1:44 12 Jan '10  
hi dear,
i want have source code VB6 for send SMS messages for sony ericsson mobile?
can you help me about?
my email is maziarmalaki69@yahoo.com
thanks.
GeneralThe value 86 is not part of the 7-bit default alphabet extension table.
Member 4452091
22:46 6 Jan '10  
Hi,

I faced the following problem while reading the SMS from GSM modem of micromax.

The value 86 is not part of the 7-bit default alphabet extension table.

If somebody know the solution please give me. Its very urgent


Thanks
QuestionHow can I send SMS to more than 140 characters of Unicode to use your Dll.
Ir-win ChakadCo
21:02 2 Jan '10  
Hello.
My question about your post "How To Send and Receive SMS using GSM Modem" is.
How can I send SMS to more than 140 characters of Unicode to use your Dll.
When sending SMS to the following error:
"Text is too Long. A Maximum of 140 resulting octets is fellowed.The current input results in 268 octets"

tasks
AnswerRe: How can I send SMS to more than 140 characters of Unicode to use your Dll.
dafsfasfaasfda
19:07 12 Mar '10  
unfortunatly nobody give u the answer
Generalprogrammetically reset the gs modem while in a sleeping mode
07aneesh
20:52 23 Dec '09  
hi

How to programmetically reset the gs modem while in a sleeping mode.Now i am using the benq gsm modem.I developed an sms website.I faced one problem,the modem is in an idle state( means not used in some hours )after that the port is not opened so i couldn't send the message.How can i solve this problem.Pls help Urgently.ok
Regards
Aneesh A S
07aneesh@gmail.com
Generalhtc with windows mobile 6.1os
bakasur
3:03 21 Dec '09  
i have an HTC touch viva phone which is on windows mobile 6.1 os. can i use this application with it?? can active sync be used to make a serial connection? what are the settings required?
please reply asap
GeneralSonyEricsson problem
mahmoud ankeer
19:36 4 Dec '09  
Dear Mr. Ranjan D

I have the following problem, I'm trying to read the contacts from phone DB but unfortunately the program is hanging, I have a sony ericsson K600i, and I tested also on sony ericsson k800i.

please help me as soon as possible. since my customer in hurry.

Best Regards.
GeneralRe: SonyEricsson problem
sgsiva
20:10 20 Dec '09  
Hi,

please Use K750i. and aslo use correct com port.


S.G. SIVA M.C.A.,
+919865943001

General"no data received from phone after waiting xxx" error using Samsung J700i
vjay01
4:28 29 Nov '09  
hi, can anyone help me on this? i received this message box when trying to read the messages on the Samsung J700i phone. it seems that the GSMComm cannot read the inbox of the phone. does anyone has a solution to this problem? thanks.
Generalproblem in receiving incoming message
amit_bid
20:45 26 Nov '09  
dear ranjan sir
you didnt reply my previous query,i m in dilemma bcz i am not able to receive message while running application through GSM modem.Please reply me
GeneralRe: problem in receiving incoming message
Ranjan.D
21:29 26 Nov '09  
Hi,

Can you please explain wht exactly the problem is? Did you debuged the application when you receive message?
I will be on vacation for a week so will look into this and replay back after I coming back..

Thanks,

Ranjan.D

GeneralRe: problem in receiving incoming message
amit_bid
23:57 26 Nov '09  
Sir actually the problem which encounterd is that when i send a sms on sim which is inserted in GSm modem,that message is not reading by this dot net application(read message list does not show that new message) however we can read that message with the help of Hyperterminal.so please help me how to overcome by this issue.its urgent sir
thanks in Advance
Generalmessage sending is not running,message error 515 while sending message
amit_bid
1:59 26 Nov '09  
message sending is not running,message error 515 while sending message, Cry
GeneralUnable to open port COM1: Unable to open COM1 Access is denied" How to close the port programetically
07aneesh
18:50 23 Nov '09  
hi

I tried this code.It is a great one.But i occured one exception during the port opening time .The error is "Unable to open port COM1: Unable to open COM1 Access is denied".My question is at the time of exception how to close the port programetically.I tried the following code but it returns false.

if (com.IsOpen())
com.close();

How can i close this port programetically.Urgent pls reply.
Regards Aneesh A S
e-mail-07aneesh@gmail.com
GeneralRe: Unable to open port COM1: Unable to open COM1 Access is denied" How to close the port programetically
Ranjan.D
1:42 26 Nov '09  
COM1 Access is denied occurs when you already have an Open connection to same COM port.
The Close() method of Serial Communication class can be used to close the open COM port connection. I dont think you will find any issues with Close() menthod. Please try and let me know

Thanks,

Ranjan.D


Last Updated 10 Sep 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010