The method of java SMS cat sending SMS

java is used to realize the function of sending and receiving short messages. At present, there are three ways to realize the function of group sending short messages in general projects

·1. Apply for SMS gateway to the operator without additional equipment, and use the API calling program provided by the operator to send SMS, which is suitable for large-scale communication companies.

·2. With the help of devices such as GSM MODEM (mobile phones that support AT command are OK), send SMS by connecting data lines to computers. This method is more suitable for small companies and individuals. In order to realize this way, we must understand serial communication, AT instruction, short message coding and decoding.

·3. With the help of a third-party website, the website sends SMS data on behalf of the website. This method is too dependent on the website and requires a high level of network.


In view of the situation of the project and various considerations, AT the same time, we found an open-source SMSLib project support, which is more inclined to the second method. The emergence of SMSLib does not require us to write the underlying AT instructions, so we can directly call the API of SMSLib to receive and send SMS through GSM modem.

Official website of SMSLib: http://smslib.org/ , some basic points of using SMSLib:

·SUN JDK 1.6 or newer

·Java Communications Library

·Apache ant for building the sources

·Apache log4j

·Apache Jakarta Commons -NET

·JSMPP Library (required for SMPP protocol)


Additional instructions for Java serial communication are required:

·SUN Java Comm v2 can be used for Windows system

Download address: http://smslib.googlecode.com/files/javacomm20-win32.zip

·Other operating systems (such as Linux, Unix, BSD, etc.), you can choose Java Comm v3 or RxTx.

Java Comm v3 download address: http://java.sun.com/products/javacomm/ (registration required)
RxTx official website: http://users.frii.com/jarvi/rxtx/index.html or http://rxtx.qbang.org/wiki/index.php/Main_Page


The attachment provides relevant downloads:

·java serial communication v2: javacomm20-win32.zip

·                 smslib-3.5.1.jar

·SMS modem driver: PL2303_Prolific_DriverInstaller_v130.zip


The environment of this test is window, and GSM modem is wavecom, so this test mainly describes the simple implementation process under the window environment:
[1] , configure the corresponding environment
First, unzip the downloaded Java Comm v2 file javacomm20-win32.zip. The specific configuration steps are as follows:


·Put the file: comm.jar copy to the directory: JDKDIR/jre/lib/ext /. Of course, this step can also be avoided. You only need to copy comm.jar to the corresponding lib / of the project you want to run

·Put the file: javax.comm.propertiescopy into the directory: JDKDIR/jre/lib/

·copy the DLL file: win32com.dll (windows) to the directory: JDKDIR/jre/bin/

If there is a JRE directory, it is better to copy the file to the corresponding directory of JREDIR in the above steps

Test serial port program:
Test .java

Java code

package test;

 

import java.util.Enumeration;

 

import javax.comm.CommDriver;

import javax.comm.CommPortIdentifier;

import javax.comm.SerialPort;

 

public class Test {

 

  public static void main(String[] args) throws Exception {  

       // Manual loading drive  

       // MainTest.driverInit();  

  Test.getCommPortList();  

       // Manual load driver get port list  

       // TestGetPortList.getPortByDriver();  

 

   }  

 

   /** 

    * Manual load driver < br > 

    * Under normal circumstances, the program will automatically load the driver, so it is usually not necessary to manually load < br > 

    * Every time the port is loaded repeatedly, the port will be registered repeatedly, and the port obtained by CommPortIdentifier.getPortIdentifiers() will be repeated 

    */  

   public static void driverManualInit() {  

       String driverName = "com.sun.comm.Win32Driver";  

       String libname = "win32com";  

       CommDriver commDriver = null;  

       try {  

           System.loadLibrary("win32com");  

           System.out.println(libname + " Library Loaded");  

 

           commDriver = (javax.comm.CommDriver) Class.forName(driverName)  

                   .newInstance();  

           commDriver.initialize();  

           System.out.println("comm Driver Initialized");  

 

       } catch (Exception e) {  

           System.err.println(e);  

       }  

   }  

 

   /** 

    * Get port list 

    */  

   public static void getCommPortList() {  

       CommPortIdentifier portId;  

       Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();  

       while (portEnum.hasMoreElements()) {  

           portId = (CommPortIdentifier) portEnum.nextElement();  

 

           if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {  

               System.out.println("Serial port: name-" + portId.getName()  

                       + " Whether to occupy or not-" + portId.isCurrentlyOwned());  

           } else {  

               System.out.println("Parallel port: name-" + portId.getName()  

                       + " Whether to occupy or not-" + portId.isCurrentlyOwned());  

           }  

       }  

       System.out.println("-------------------------------------");  

   }  

 

   /** 

    *  

    */  

   public static void getPortByDriver() {  

 

       String driverName = "com.sun.comm.Win32Driver";  

       String libname = "win32com";  

       CommDriver commDriver = null;  

       try {  

           System.loadLibrary("win32com");  

           System.out.println(libname + " Library Loaded");  

 

           commDriver = (CommDriver) Class.forName(driverName).newInstance();  

           commDriver.initialize();  

           System.out.println("comm Driver Initialized");  

 

       } catch (Exception e) {  

           System.err.println(e);  

       }  

       SerialPort sPort = null;  

       try {  

 

           sPort = (SerialPort) commDriver.getCommPort("COM24",  

                   CommPortIdentifier.PORT_SERIAL);  

           System.out.println("find CommPort:" + sPort.toString());  

       } catch (Exception e) {  

           System.out.println(e.getMessage());  

       }  

 

   }  

 

}

 


 


Local operation result:

Quote


Serial port: name-COM10 occupied - false
Serial port: name-COM21 occupied - false
Serial port: name-COM23 occupied - false
Serial port: name-COM20 occupied - false
Serial port: name-COM22 occupied - false
Serial port: name-COM24 occupied - false
Serial port: name-COM9 occupied - false
Serial port: name-COM19 occupied - false
Serial port: name-COM3 occupied - false
Serial port: name-COM8 occupied - false
Serial port: name-COM98 occupied - false
Serial port: name-COM99 occupied - false
Serial port: name-COM4 occupied - false
Serial port: name-COM5 occupied - false
Serial port: name-COM6 occupied - false
Parallel port: name LPT1 occupied - false
Parallel port: name lpt2 occupied - false
-------------------------------------


















[3] . check serial device information:
TestCommPort .java

Java code

package test;

 

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

 

import javax.comm.CommPortIdentifier;

import javax.comm.SerialPort;

 

public class TestCommPort {

  

    static CommPortIdentifier portId;  

    static Enumeration portList;  

    static int bauds[] = { 9600, 19200, 57600, 115200 };  

  

    /** 

     * @param args 

     */  

    public static void main(String[] args) {  

        portList = CommPortIdentifier.getPortIdentifiers();  

        System.out.println("GSM Modem Serial port connection test start...");  

        String portName = "COM4";  

        while (portList.hasMoreElements()) {  

            portId = (CommPortIdentifier) portList.nextElement();  

            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL  

                    && portName.equals(portId.getName())) {  

                System.out.println("Find serial 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;  

                        StringBuffer response = new StringBuffer();  

                        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(1000);  

                        c = inStream.read();  

                        while (c != -1) {  

                            c = inStream.read();  

                        }  

                        outStream.write('A');  

                        outStream.write('T');  

                        outStream.write('\r');  

                        try {  

                            Thread.sleep(1000);  

                        } catch (Exception e) {  

                        }  

                        c = inStream.read();  

                        while (c != -1) {  

                            response.append((char) c);  

                            c = inStream.read();  

                        }  

                        if (response.indexOf("OK") >= 0) {  

                            System.out.print("  Detecting device:");  

                            try {  

                                outStream.write('A');  

                                outStream.write('T');  

                                outStream.write('+');  

                                outStream.write('C');  

                                outStream.write('G');  

                                outStream.write('M');  

                                outStream.write('M');  

                                outStream.write('\r');  

                                response = new StringBuffer();  

                                c = inStream.read();  

                                while (c != -1) {  

                                    response.append((char) c);  

                                    c = inStream.read();  

                                }  

                                System.out.println("  devices detected: "  

                                        + response.toString().replaceAll(  

                                                "(\\s+OK\\s+)|[\n\r]", ""));  

                            } catch (Exception e) {  

                                System.out.println("  Test device failed,Exception in obtaining device information:"  

                                        + e.getMessage());  

                            }  

                        } else {  

                            System.out.println("  Test device failed, no response received!");  

                        }  

                        serialPort.close();  

                    } catch (Exception e) {  

                        System.out.println("  Test device failed with exception:" + e.getMessage());  

                    }  

                }  

            }  

        }  

    }  

}  

 


 


The operation results are as follows:

Quote


GSM Modem serial port connection test started
Find serial port: COM24
Trying at 9600... Detecting device: discovering device: AT+CGMM MULTIBAND 900E 1800
Trying at 19200... Failed to find device, no response received
Trying at 57600... Failed to find device, no response received
Trying at 115200... Failed to find device, no response received!






[4] . test SMS:

Java code

package test;

 

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.List;

 

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import org.smslib.AGateway;

import org.smslib.AGateway.Protocols;

import org.smslib.GatewayException;

import org.smslib.InboundMessage;

import org.smslib.Message.MessageEncodings;

import org.smslib.OutboundMessage;

import org.smslib.Service;

import org.smslib.modem.SerialModemGateway;

 

public class SendSmsHandler {  

    private static final Logger logger = Logger.getLogger(SendSmsHandler.class);  

  

    private Service smsService;  

  

    /** 

     * Send SMS class

     */  

    public SendSmsHandler() {  

        smsService = Service.getInstance();  //Get the

        List<AGateway> agatewayList = new ArrayList<AGateway>();  

  

        String portName = "COM4";//"/dev/ttyUSB0";// COM24  //Port number used

        SerialModemGateway gateway = new SerialModemGateway(  

                "modem." + portName, portName, 9600, "wavecom", "PL2303");  //Obtain device instance through port number, frequency name and other contents

        gateway.setInbound(true);  

        gateway.setOutbound(true);  

        gateway.setProtocol(Protocols.PDU);  //Send all PDU

        gateway.setSimPin("0000");  

        agatewayList.add(gateway);  //Put it in the queue, you can put more than one in the group

        try {  

            for (AGateway gatewayTmp : agatewayList) {  

                smsService.addGateway(gatewayTmp);  

            }  

        } catch (GatewayException ex) {  

            logger.error(ex.getMessage());  

        }  

    }  

  

    /** 

     *  Start SMS service

     */  

    public void start() {  

        logger.info("SMS service start.....");  

        try {  

            smsService.startService();  

        } catch (Exception ex) {  

            logger.error("SMS service start error:", ex);  

        }  

    }  

  

    /** 

     *  Stop sending SMS

     */  

    public void destroy() {  

        try {  

            smsService.stopService();  //Out of Service

        } catch (Exception ex) {  

            logger.error("SMS service stop error:", ex);  

        }  

        logger.info("SMS service stop");  

    }  

  

    /** 

     * send SMS 

     * How to send SMS

     * @param msg Sent content

     * @return Boolean Return whether to send successfully

     */  

    public Boolean sendSMS(OutboundMessage msg) {  

        try {  

            msg.setEncoding(MessageEncodings.ENCUCS2);  //Set encoding

            return smsService.sendMessage(msg);  //Send SMS and return results

        } catch (Exception e) {  

            logger.error("send error:", e);  

        }  

        return false;  

    }  

  

//Is the service started

    private boolean isStarted() {  

        if (smsService.getServiceStatus() == Service.ServiceStatus.STARTED) {  //Whether the status of the service is start

            for (AGateway gateway : smsService.getGateways()) {  

                if (gateway.getStatus() == AGateway.GatewayStatuses.STARTED) {  

                    return true;  

                }  

            }  

        }  

        return false;  

    }  

  

    /** 

     * read SMS To read the received message

     * @return List 

     */  

    public List<InboundMessage> readSMS() {  

        List<InboundMessage> msgList = new LinkedList<InboundMessage>();  

        if (!isStarted()) {  

            return msgList;  

        }  

        try {  

            this.smsService.readMessages(msgList,  

                    InboundMessage.MessageClasses.ALL);  

            logger.info("read SMS size: " + msgList.size());  

        } catch (Exception e) {  

            logger.error("read error:", e);  

        }  

        return msgList;  

    }  

  

    /** 

     * @param args Test class

     */  

    public static void main(String[] args) {  

        Logger.getRootLogger().setLevel(Level.INFO);  

        OutboundMessage outMsg = new OutboundMessage("189*****", "Information test");  //Binding received phone numbers and messages sent

        SendSmsHandler smsHandler = new SendSmsHandler();  

        smsHandler.start();  //start-up

        //Sending SMS  

        smsHandler.sendSMS(outMsg);  

        //Read SMS  

        List<InboundMessage> readList = smsHandler.readSMS();  

        for (InboundMessage in : readList) {  

            System.out.println("Addressee:" + in.getOriginator() + " Content of short message:"  

                    + in.getText());  

        }  

        smsHandler.destroy();  //Out of Service

        System.out.println("-----------");  

    }  

  

}

 


 


Send SMS to test, mobile phone can receive display normally. The result of reading the SMS program of the device is as follows:

Quote


INFO - Service.listSystemInformation(113) | SMSLib: A Java API library forsending and receiving SMS via a GSM modem or other supported gateways. 
This software is distributed under the terms of the Apache v2.0 License. 
Web Site: http://smslib.org 
INFO - Service.listSystemInformation(114) | Version: 3.5.1 
INFO - Service.listSystemInformation(115) | JRE Version: 1.6.0_18 
INFO - Service.listSystemInformation(116) | JRE Impl Version: 16.0-b13 
INFO - Service.listSystemInformation(117) | O/S: Windows Vista / x86 /6.0 
INFO - SmsHandler.start(55) | SMS service start..... 
INFO - DefaultQueueManager.init(92) | Queue directory not defined. Queuedmessages will not be saved to filesystem. 
INFO - ModemGateway.startGateway(188) | GTW: modem.COM24: Starting gateway,using Generic AT Handler. 
INFO - SerialModemDriver.connectPort(68) | GTW: modem.COM24: Opening: COM24@9600 
INFO - AModemDriver.waitForNetworkRegistration(459) | GTW: modem.COM24: GSM:Registered to foreign network (roaming). 
INFO - AModemDriver.connect(175) | GTW: modem.COM24: MEM: Storage LocationsFound: SMBM 
INFO - CNMIDetector.getBestMatch(142) | CNMI: No best match, returning: 1 
INFO - ModemGateway.startGateway(191) | GTW: modem.COM24: Gatewaystarted. 
INFO - SmsHandler.readSMS(113) | read SMS size: 1 
Sender: 8618918001030 message content: hello reply test
INFO - ModemGateway.stopGateway(197) | GTW: modem.COM24: Stoppinggateway... 
INFO - SerialModemDriver.disconnectPort(120) | GTW: modem.COM24: Closing: COM24@9600 
INFO - ModemGateway.stopGateway(201) | GTW: modem.COM24: Gateway stopped. 
INFO - SmsHandler.destroy(72) | SMS service stop 
-----------



























Tags: Java Apache log4j Windows

Posted on Fri, 17 Apr 2020 23:09:47 -0700 by mburkwit