`
thtwin
  • 浏览: 165042 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

java-发短信(duanxinmao)

阅读更多
import javax.comm.*;
import java.util.*;
import java.io.*;
import org.smslib.*;

public class smsModem
{
    private static  LinkedList<COutgoingMessage> msgList = new LinkedList<COutgoingMessage>();
    private static String com="";
    private static int baudRate=0;
    private static CService srv;
    private static boolean isSending=false;

    private static   void  testAndSetCom()
        /**
        Try to find out which com port is used by modem and the work baudrate.
        */
        {
        CommPortIdentifier portId;
        Enumeration portList;
        //int bauds[] = { 9600, 19200, 38400, 115200 };
        int bauds[]={38400, 115200};
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements())
            {
            portId = (CommPortIdentifier) portList.nextElement();
            System.out.println("PORTID:"+portId);
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                {
                System.out.println("Found port: " + portId.getName());
                for (int i = 0; i < bauds.length; i++)
                    {
                    System.out.print("    Trying at " + bauds[i] + "...");
                    try
                        {
                        SerialPort serialPort;
                        InputStream inStream;
                        OutputStream outStream;
                        int c;
                        String response;

                        serialPort = (SerialPort) portId.open("SMSLibCommTester", 1971);
                        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
                        serialPort.setSerialPortParams(bauds[i], SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                        inStream = serialPort.getInputStream();
                        outStream = serialPort.getOutputStream();
                        serialPort.enableReceiveTimeout(2000);
                        c = inStream.read();
                        while (c != -1)
                            c = inStream.read();
                        outStream.write('A');
                        outStream.write('T');
                        outStream.write('\r');
                        outStream.write('A');
                        outStream.write('T');
                        outStream.write('\r');
                        outStream.write('A');
                        outStream.write('T');
                        outStream.write('\r');
                        try { Thread.sleep(1000); } catch (Exception e) {}
                        response = "";
                        c = inStream.read();
                        while (c != -1)
                        {
                            response += (char) c;
                            c = inStream.read();
                        }
                        serialPort.close();
                        if (response.indexOf("OK") >= 0)
                        {    setCom(portId.getName());
                            setBaud(bauds[i]);
                            System.out.print("  Getting Info...");
                            startSrv();
                            System.out.println("  Found: " + srv.getDeviceInfo().getModel());
                            stopSrv();
                        }
                        else System.out.println("  Nobody here!");
                    }
                    catch (Exception e)
                        {
                        System.out.println("  Nobody here!");
                        }
                    }
                }
            }
        if (com == "" && baudRate ==0)
                {System.out.println("Didn't find any useable com port");}
        }

    private static void showModemInformation()
        /**
        Get the modem information.
        */
        {
        System.out.println("Getting modem information ...");
        if (com == "" && baudRate ==0)
            {System.out.println("Haven't got any useable com port yet! Run testAndSetCom() at first. ");
             System.exit(1);}
        //sendTest.srv = new CService(com, baudRate, "wavecom", "");
        startSrv();
        System.out.println();
        System.out.println("ReadMessages: Synchronous Reading.");
        System.out.println("  Using " + CService._name + " " + CService._version);
        System.out.println();       
       
        //srv.setSimPin("0000");
        // OK, let connect and see what happens... Exceptions may be thrown
        // here!
        // Lets get info about the GSM device...
        System.out.println("Mobile Device Information: ");
        System.out.println("    Manufacturer  : " + srv.getDeviceInfo().getManufacturer());
        System.out.println("    Model         : " + srv.getDeviceInfo().getModel());
        System.out.println("    Serial No     : " + srv.getDeviceInfo().getSerialNo());
        System.out.println("    IMSI          : " + srv.getDeviceInfo().getImsi());
        System.out.println("    S/W Version   : " + srv.getDeviceInfo().getSwVersion());
        System.out.println("    Battery Level : " + srv.getDeviceInfo().getBatteryLevel() + "%");
        System.out.println("    Signal Level  : " + srv.getDeviceInfo().getSignalLevel() + "%");
        System.out.println("    GPRS Status   : " + (srv.getDeviceInfo().getGprsStatus() ? "Enabled" : "Disabled"));
        System.out.println("");
        // Write your test calls here.
        // ...
        // ...
        stopSrv();
        //System.exit(0);
    }

   



    private static String getCom()
        /**
            get the com port.
        */
        {
        return com;
        }
   
    private static int getBaud()
        /**
            get the baudrate.
        */
        {
        return baudRate;
        }
   
    private static void setCom(String comport)
        /**
            set com port manually.
        */
        {
        com=comport;
        }
   
    private static void setBaud(int baud)
        /**
            set baudrate manually.
        */
        {
        baudRate=baud;
        }
   
    private static void startSrv()
        /**
            start the CService
        */
        {
        srv=new CService(getCom(), getBaud(), "", "");
        try
                {
                    srv.connect();
                    System.out.println(" srv starts now... " );
                }
        catch (Exception e)
                {
                    System.out.println(e);
                }
        }
   
    private static void stopSrv()
        /**
            stop the CService
        */
        {try
            {
            srv.disconnect();
            System.out.println( "srv stops now..." );
            }
         catch (Exception e)
                {
                    System.out.println(e);
                }
        }

    /**
    For outside usage.
    Start the sms modem.
    */
    public static boolean startModem()
        {
        testAndSetCom();
        showModemInformation();       
        sendInitial();
        return isReady();
        }

    /**
    For outside usage.
    Stop the sms modem.
    */
    public static boolean stopModem()
        {try
            {
            srv.disconnect();
            System.out.println( "srv stops now..." );
            }
         catch (Exception e)
                {
                    System.out.println(e);
                }
         return !(isReady());
        }

    /**
    For outside usage.
    Return the status (connected or not ) of sms modem.
    */
    public static boolean isReady()
        {
        return srv.getConnected() ;
        }
   
    private static synchronized void sendingLock()
        {
        isSending = true ;
        }
    private static synchronized void sendingUnlock()
        {
        isSending = false;
        }
    private static synchronized boolean isSending()
        {return isSending;}


    /**
    For outside usage.
    Add warning message list.
    */
    public static void addWarning(ArrayList<String> numberList,String content)
        {for (int i=0;i<numberList.size();i++)
            {
                COutgoingMessage msg = new COutgoingMessage(numberList.get(i),content);
                InsertWarningMsgToList(msg);
            }
        Thread send = new Thread( new Runnable() {public void run(){if(!(isSending())){sendingLock();System.out.println("Processing");startSending();sendingUnlock();}else{System.out.println("Have started processing yet, so return now.");return;}}});
        send.setDaemon(true);
        send.start();
        }
    /**
    For outside usage.
    Add task message list.
    */
    public static void addTask(ArrayList<String> numberList,String content)
        {for (int i=0;i<numberList.size();i++)
            {
                COutgoingMessage msg = new COutgoingMessage(numberList.get(i),content);
                InsertTaskMsgToList(msg);
               
            }
        Thread send = new Thread( new Runnable() {public void run(){if(!(isSending())){sendingLock();System.out.println("Processing");startSending();sendingUnlock();}else{System.out.println("Have started processing yet, so return now.");return;}}});
        send.setDaemon(true);
        send.start();
        }
   
    private static void startSending()
        {
        while (msgSize()>0)
            {sendMsg(getMessage());}
        }
           
   
    private static synchronized  void  InsertWarningMsgToList(COutgoingMessage msg)
        /** Insert outgoing msg to msg list
        */
        { msgList.add(0,msg);}
    private static synchronized boolean  InsertTaskMsgToList(COutgoingMessage msg)
        /** Insert outgoing msg to msg list
        */
        { return msgList.add(msg);}
    public static synchronized COutgoingMessage getMessage()
        {
        return msgList.poll();
        }

   
    //public static  synchronized boolean  makeAndInsertMsg(String number,String content)
        /**
        use number,content to consist of  an outgoing msg and insert this msg to msg list
        */
    //    {
    //    COutgoingMessage msg = new COutgoingMessage(number, content);
    //    return InsertMsgToList(msg);
    //    }
    //public static void makeAndInsertMsgFromList(ArrayList<String> numberList,String content)
        /**
        make outgoing msgs for all the recipients recorded in numberList, these msgs have the same content.
        */
    //    {
    //    int cnt;
    //    for (cnt=0;cnt<numberList.size();cnt++)
    //        {
    //        makeAndInsertMsg(numberList.get(cnt), content);
    //        }
    //    }
   
    private static synchronized int msgSize()
        {
        return msgList.size();
        }
    private static boolean msgEmpty()
        {
        return msgSize() == 0;
        }

    private static void sendInitial()
        { System.out.println("Initialization for sending message ...");
          try {
              // If the GSM device is PIN protected, enter the PIN here.
            // PIN information will be used only when the GSM device reports
            // that it needs a PIN in order to continue.
              srv.setSimPin("0000");
            // Some modems may require a SIM PIN 2 to unlock their full functionality.
            // Like the Vodafone 3G/GPRS PCMCIA card.
            // If you have such a modem, you should also define the SIM PIN 2.
            srv.setSimPin2("0000");
            // Normally, you would want to set the SMSC number to blank. GSM
            // devices get the SMSC number information from their SIM card.
            srv.setSmscNumber("");
           
            srv.setProtocol(0);
            startSrv();
              }
           catch (Exception e)
            {
            e.printStackTrace();
            }
        }
    /**
    This function is used for sending message. Before using it ,you must run sendInitial() at first,and do not forget close() the srv after sending message.
    */
    private static void sendMsg(COutgoingMessage msg)
        {
        System.out.println("Sending Message ...");
           

            // Lets get info about the GSM device...
            //System.out.println("Mobile Device Information: ");
            //System.out.println("    Manufacturer  : " + srv.getDeviceInfo().getManufacturer());
            //System.out.println("    Model         : " + srv.getDeviceInfo().getModel());
            //System.out.println("    Serial No     : " + srv.getDeviceInfo().getSerialNo());
            //System.out.println("    IMSI          : " + srv.getDeviceInfo().getImsi());
            //System.out.println("    S/W Version   : " + srv.getDeviceInfo().getSwVersion());
            //System.out.println("    Battery Level : " + srv.getDeviceInfo().getBatteryLevel() + "%");
            //System.out.println("    Signal Level  : " + srv.getDeviceInfo().getSignalLevel() + "%");

            // Lets create a message for dispatch.
            // A message needs the recipient's number and the text. Recipient's
            // number should always be defined in international format.
           
            //COutgoingMessage msg = new COutgoingMessage("+306948494037", "Message from SMSLib for Java.");

            // Set the message encoding.
            // We can use 7bit, 8bit and Unicode. 7bit should be enough for most
            // cases. Unicode is necessary for Far-East countries.
            msg.setMessageEncoding(CMessage.MessageEncoding.EncUcs2);

            // Do we require a Delivery Status Report?
           
               
            msg.setStatusReport(true);

                //// We can also define the validity period.
            //// Validity period is always defined in hours.
            //// The following statement sets the validity period to 8 hours.
            //msg.setValidityPeriod(8);

            // Do we require a flash SMS? A flash SMS appears immediately on
            // recipient's phone.
            // Sometimes its called a forced SMS. Its kind of rude, so be
            // careful!
            // Keep in mind that flash messages are not supported by all
            // handsets.
            // msg.setFlashSms(true);

            // Some special applications are "listening" for messages on
            // specific ports.
            // The following statements set the Source and Destination port.
            // They should always be used in pairs!!!
            // Source and Destination ports are defined as 16bit ints in the
            // message header.
            // msg.setSourcePort(10000);
            // msg.setDestinationPort(11000);

            // Ok, finished with the message parameters, now send it!
            // If we have many messages to send, we could also construct a
            // LinkedList with many COutgoingMessage objects and pass it to
            // srv.sendMessage().
            try {
            srv.sendMessage(msg);   
                    }catch (Exception e)
            {
            e.printStackTrace();
            }
        }
       
    public static void main(String[] args)
        {
        //testAndSetCom();
        //showModemInformation();
        //setCom("COM1");
        //setBaud(115200);
        //srv=new CService(getCom(), getBaud(), "", "");
        //System.out.println("com:"+sendTest.getCom());
        //System.out.print("BaudRate: ");
        //System.out.println(sendTest.getBaud());
        //sendTest.makeAndInsertMsg("1381122xxxx","Hi,how are  you!!! Happy every day!");
        //makeAndInsertMsg("10086","ye");
        //System.out.println(sendTest.msgSize());
        //sendInitial();
        //sendMsg(sendTest.msgList.remove(0));
        //if (isReady()) {System.out.println("connected ...");}
        startModem();
        ArrayList<String> numberlist = new ArrayList<String>();
        numberlist.add("1381122xxxx");
        String content1="Hello. Test LinkedList.Message type: Task message.";
        String content2="Hello. Test LinkedList.Message type: Warning message.";
        addTask( numberlist,content1);
        addWarning( numberlist,content2);

        try { Thread.sleep(300000); } catch (Exception e) {}
       
        stopModem();
        //if (!isReady()) {System.out.println("disconnected ...");}
        //sendTest.msgList.remove(0);
        //System.out.println(sendTest.msgSize());
        }
}
分享到:
评论

相关推荐

    mysql-connector-java-5.1.40.zip和mysql-connector-java-5.1.10.jar

    本文将深入探讨这两个文件:"mysql-connector-java-5.1.40.zip" 和 "mysql-connector-java-5.1.10.jar",以及它们在Java开发中的作用。 首先,`mysql-connector-java-5.1.40.zip` 是一个压缩文件,包含了MySQL ...

    aliyun-java-sdk-dysmsapi-1.1.0.jar

    aliyun-java-sdk-dysmsapi-1.1.0.jar 最新下载的 阿里云短信服务器所需jar包之一,core包可以在maven找到不再上传 &lt;!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-dysmsapi --&gt; ...

    aliyun-java-sdk-core-4.1.0.jar 阿里大于短信发送的依赖包

    在这个场景中,"aliyun-java-sdk-core-4.1.0.jar" 是一个Java版本的核心SDK,主要用于与阿里大于的各项服务进行交互,特别是短信发送功能。 一、阿里大于SDK核心功能 1. **身份验证**:SDK提供了基于AccessKey的...

    mysql-connector-java-5.1.7 jar包

    MySQL是世界上最流行的开源关系型数据库管理系统之一,而`mysql-connector-java-5.1.7.jar`是MySQL官方为了使得Java应用程序能够连接到MySQL数据库而提供的JDBC(Java Database Connectivity)驱动程序。JDBC是Java...

    mysql-connector-java-5.1.40.tar.gz

    "mysql-connector-java-5.1.40.tar.gz" 是这个驱动程序的一个特定版本,版本号为5.1.40。这个压缩包包含了运行Java应用与MySQL数据库进行交互所需的类库和其他相关文件。 在Linux环境中处理这个压缩包,首先需要将...

    mysql驱动包mysql-connector-java-5.1.7-bin.jar

    mysql-connector-java-5.1.7-bin.jar

    mysql-connector-java-8.0.11.jar

    `mysql-connector-java-8.0.11.jar`适用于较新的MySQL环境,`mysql-connector-java-5.1.7-bin.jar`满足了对老版本MySQL的兼容需求,而`ojdbc14-10.2.0.1.0.jar`则服务于Oracle 10g数据库。在Java开发中,理解如何...

    ckeditor-java-core-3.5.3

    此版本是"ckeditor-java-core-3.5.3",专门针对Java平台进行了优化,允许开发者在Java应用程序中集成CKEditor的功能。 1. **CKEditor简介** CKEditor是一款基于JavaScript的WYSIWYG(所见即所得)文本编辑器,最初...

    mysql-connector-java-8.0.18.jar

    这是MySQL最新的jar,mysql-connector-java-8.0.18.jar

    mysql驱动包 mysql-connector-java-5.1.13-bin.jar

    mysql驱动包 mysql-connector-java-5.1.13-bin.jar 方便快捷获取。。。

    mysql-connector-java-commercial-5.1.30-bin.jar

    将要使用的是mysql-connector-java-5.1.30-bin-g.jar和mysql-connector-java-5.1.30-bin.jar 配置 在C:\Program Files\Java目录下建立mysqlforjdbc子目录,进入该目录将mysql-connector-java-5.1.30-bin.jar到该...

    基于java的开发源码-手机短信项目源码.zip

    基于java的开发源码-手机短信项目源码.zip 基于java的开发源码-手机短信项目源码.zip 基于java的开发源码-手机短信项目源码.zip 基于java的开发源码-手机短信项目源码.zip 基于java的开发源码-手机短信项目源码.zip ...

    mysql-connector-java-8.0.27.jar

    mysql-connector-java-8.0.27.jar包下载

    基于java的开发源码-发送短信包 LemonSMS.zip

    基于java的开发源码-发送短信包 LemonSMS.zip 基于java的开发源码-发送短信包 LemonSMS.zip 基于java的开发源码-发送短信包 LemonSMS.zip 基于java的开发源码-发送短信包 LemonSMS.zip 基于java的开发源码-发送短信...

    aliyun-java-sdk-dysmsapi-1.0.0

    最新下载的 阿里云短信服务器所需jar包之一,... &lt;artifactId&gt;aliyun-java-sdk-core &lt;version&gt;3.2.2 如此引用即可,更多关于阿里云短信发送相关请参考http://blog.csdn.net/niaoer2010/article/details/78036664

    mysql-connector-java-8.0.22

    mysql-connector-java-8.0.22,支持Java1.8,方便大家使用放这里了。已测试通过,谢谢

    java图片处理工具类JAR包 java-image-scalingjar

    java图片处理工具类JAR包 java-image-scalingjar

    mysql-connector-java-8.0.31-jar包

    本资源提供的"mysql-connector-java-8.0.31-jar包"正是这样一个驱动程序的最新版本,即8.0.31。 MySQL Connector/J 8.0.31版本包含了对MySQL 8.x系列数据库的全面支持,提供了许多新特性和改进。以下是一些关键知识...

    mysql-connector-java-5.1.25.jar(用于JAVA连MySQL驱动)

    JAVA连MySQL驱动mysql-connector-java-5.1.25.jar

    mysql-connector-java-5.1.15-bin.jar

    "mysql-connector-java-5.1.15-bin.jar"是这个驱动程序的一个特定版本,版本号为5.1.15。 在Java编程环境中,当你需要连接到MySQL数据库时,你需要在类路径中包含这个JAR文件。JDBC驱动程序主要分为四种类型:Type ...

Global site tag (gtag.js) - Google Analytics