⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smsporter.java

📁 试用JAVA通过COMM口发送短信的代码.
💻 JAVA
字号:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   SMSPorter.java

package org.cross.sms.serialPort;

import java.io.*;
import java.util.*;
import javax.comm.*;
import org.cross.sms.msg.*;

public class SMSPorter
    implements SerialPortEventListener
{

    public SMSPorter(String port)
    {
        _SYNC_ = new Object();
        baud = 9600;
        timeStamp = 0L;
        this.port = port;
    }

    public boolean open()
        throws Exception
    {
        boolean result = false;
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        do
        {
            if(!portList.hasMoreElements())
                break;
            CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement();
//            System.out.println(portId.getName());
            
            if(portId.getPortType() == 1 && portId.getName().equalsIgnoreCase(port))
            {
                serialPort = (SerialPort)portId.open("Modemn", 5000);
                System.out.println("serial name is :" + serialPort.getName());
                serialPort.notifyOnDataAvailable(true);
                serialPort.notifyOnOutputEmpty(true);
                serialPort.notifyOnBreakInterrupt(true);
                serialPort.notifyOnFramingError(true);
                serialPort.notifyOnOverrunError(true);
                serialPort.notifyOnParityError(true);
                serialPort.setFlowControlMode(0);
                serialPort.addEventListener(this);
                serialPort.setSerialPortParams(baud, 8, 1, 0);
                serialPort.setInputBufferSize(8192);
                serialPort.setOutputBufferSize(8192);
                serialPort.enableReceiveTimeout(3000);
                inStream = serialPort.getInputStream();
                outStream = serialPort.getOutputStream();
                result = true;
            }
        } while(true);
        return result;
    }

    public void close()
    {
        try
        {
            serialPort.close();
        }
        catch(Exception e) { }
    }

    public void serialEvent(SerialPortEvent event)
    {
        switch(event.getEventType())
        {
        case 1: // '\001'
        case 2: // '\002'
        case 3: // '\003'
        case 4: // '\004'
        case 5: // '\005'
        case 6: // '\006'
        case 7: // '\007'
        case 8: // '\b'
        case 9: // '\t'
        case 10: // '\n'
        default:
            return;
        }
    }

    public void clearBuffer()
        throws Exception
    {
        for(; dataAvailable(); inStream.read());
    }

    private void send(String s)
        throws Exception
    {
        long newtime = (new Date()).getTime();
        if(newtime - timeStamp < 1000L)
            Thread.sleep((1000L + timeStamp) - newtime);
        timeStamp = newtime;
        if(s != null)
        {
            PrintWriter pw = new PrintWriter(outStream);
            pw.println(s);
            pw.flush();
            System.out.println(s);
        }
    }

    private void send(char c)
        throws Exception
    {
        outStream.write((byte)c);
        outStream.flush();
    }

    private void skipBytes(int numOfBytes)
        throws Exception
    {
        int count = 0;
        do
        {
            if(count >= numOfBytes)
                break;
            int c = inStream.read();
            if(c != -1)
                count++;
        } while(true);
    }

    private boolean dataAvailable()
        throws Exception
    {
        return inStream.available() > 0;
    }

    public String getResponse()
        throws Exception
    {
        int RETRIES = 3;
        int WAIT_TO_RETRY = 1000;
        int retry = 0;
        StringBuffer buffer = new StringBuffer(256);
        while(retry < 3) 
            try
            {
                do
                {
                    int c = inStream.read();
                    if(c == -1)
                    {
                        buffer.delete(0, buffer.length());
                        break;
                    }
                    buffer.append((char)c);
                } while(buffer.toString().indexOf("OK\r") <= -1 && (buffer.toString().indexOf("ERROR") <= -1 || buffer.toString().lastIndexOf("\r") <= buffer.toString().indexOf("ERROR")) && (buffer.toString().indexOf("CPIN") <= -1 || buffer.toString().indexOf("\r", buffer.toString().indexOf("CPIN")) <= -1));
                retry = 3;
            }
            catch(Exception e)
            {
                if(retry < 3)
                {
                    Thread.sleep(1000L);
                    retry++;
                } else
                {
                    throw e;
                }
            }
        if(dataAvailable())
            skipBytes(1);
        if(buffer.length() > 0)
            for(; buffer.charAt(0) == '\r' || buffer.charAt(0) == '\n'; buffer.delete(0, 1));
        String response = buffer.toString();
        System.out.println("response#" + response);
        return buffer.toString();
    }

    public String waitResponse()
        throws Exception
    {
        int RETRIES = 2;
        int WAIT_TO_RETRY = 1000;
        int retry = 0;
        StringBuffer buffer = new StringBuffer(256);
        while(retry < 2) 
            try
            {
                do
                {
                    int c = inStream.read();
                    if(c == -1)
                    {
                        buffer.delete(0, buffer.length());
                        break;
                    }
                    buffer.append((char)c);
                } while(buffer.toString().indexOf("\r") <= -1 && (buffer.toString().indexOf("ERROR") <= -1 || buffer.toString().lastIndexOf("\r") <= buffer.toString().indexOf("ERROR")) && (buffer.toString().indexOf("CPIN") <= -1 || buffer.toString().indexOf("\r", buffer.toString().indexOf("CPIN")) <= -1));
                retry = 2;
            }
            catch(Exception e)
            {
                if(retry < 2)
                {
                    Thread.sleep(1000L);
                    retry++;
                } else
                {
                    throw e;
                }
            }
        if(dataAvailable())
            skipBytes(1);
        return buffer.toString();
    }

    public boolean CMD_setPDUMode()
    {
        try {
			Object obj = _SYNC_;
//        JVM INSTR monitorenter ;
			String response;
			send("AT+CMGF=0\r");
			response = getResponse();
			if("OK".equalsIgnoreCase(response))
			    return true;
		} catch (Exception e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
//        obj;
//        JVM INSTR monitorexit ;
//        break MISSING_BLOCK_LABEL_49;
//        Exception exception;
//        exception;
//        throw exception;
//        Exception ex;
//        ex;
//        ex.printStackTrace();
        return false;
    }

    public boolean CMD_setStorageToMT()
    {
        try {
			Object obj = _SYNC_;
//        JVM INSTR monitorenter ;
			String response;
			send("AT+CPMS=\"ME\"\r");
			response = getResponse();
			if("OK".equalsIgnoreCase(response))
			    return true;
		} catch (Exception e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
//        obj;
//        JVM INSTR monitorexit ;
//        break MISSING_BLOCK_LABEL_49;
//        Exception exception;
//        exception;
//        throw exception;
//        Exception ex;
//        ex;
//        ex.printStackTrace();
        return false;
    }

    public void CMD_getUnReadRecvMsg()
    {
        try
        {
            synchronized(_SYNC_)
            {
                send(_CharacterUtil.replaceSymbol("AT+CMGL={1}\r", "{1}", "0"));
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void CMD_getAllRecvMsg()
    {
        try
        {
            send(_CharacterUtil.replaceSymbol("AT+CMGL={1}\r", "{1}", "4"));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void CMD_getReadedRecvMsg()
    {
        try
        {
            synchronized(_SYNC_)
            {
                send(_CharacterUtil.replaceSymbol("AT+CMGL={1}\r", "{1}", "1"));
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void CMD_getSendedRecvMsg()
    {
        try
        {
            synchronized(_SYNC_)
            {
                send(_CharacterUtil.replaceSymbol("AT+CMGL={1}\r", "{1}", "3"));
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public boolean CMD_delMsg(int memIndex)
    {
        Object obj = _SYNC_;
//        JVM INSTR monitorenter ;
        if(memIndex <= 0){
//        	goto _L2; else goto _L1
//        	_L2:
//                false;
//                obj;
//                JVM INSTR monitorexit ;
//                return;
                
//                exception;
                try {
                	Exception exception=new Exception();
					throw exception;
				} catch (Exception e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
				return false;
        }else{
//        	_L1:
                String response;
                try {
					send(_CharacterUtil.replaceSymbol("AT+CMGD={1}\r", "{1}", "" + memIndex));
				} catch (Exception e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
                try {
					response = getResponse();
	                if(response.indexOf("OK\r") > -1)
	                    return true;
	                return false;
	                
				} catch (Exception e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}

//                obj;
//                JVM INSTR monitorexit ;
//                return;
//                Exception e;
//                e;
//                e.printStackTrace();
//                false;
//                obj;
//                JVM INSTR monitorexit ;
//                return;
        }
		return false;


    }

    public void CMD_delAllMsg()
    {
        CMD_getReadedRecvMsg();
        LinkedList ll = readPDUMsg();
        if(ll != null)
        {
            for(int i = 0; i < ll.size(); i++)
                CMD_delMsg(((SMSMsg)ll.get(i)).memIndex);

        }
        CMD_getSendedRecvMsg();
        ll = readPDUMsg();
        if(ll != null)
        {
            for(int i = 0; i < ll.size(); i++)
                CMD_delMsg(((SMSMsg)ll.get(i)).memIndex);

        }
    }

    public LinkedList readPDUMsg()
    {
        try {
			LinkedList ll = new LinkedList();
			String response = "";
			synchronized(_SYNC_)
			{
			    response = getResponse();
			}
			BufferedReader reader = new BufferedReader(new StringReader(response));
			String line = reader.readLine();
			if(line != null)
			    line = line.trim();
			do
			{
			    if(line == null || !line.toLowerCase().startsWith("at+cmgl") && line.length() != 0)
			        break;
			    line = reader.readLine();
			    if(line != null)
			        line = line.trim();
			} while(true);
			for(; line != null && line.length() > 0 && !line.equalsIgnoreCase("OK") && !line.equalsIgnoreCase("ERROR"); line = reader.readLine().trim())
			{
			    int i = line.indexOf(':');
			    int j = line.indexOf(',');
			    if(i <= 0 || j <= 0)
			        continue;
			    int memIndex = Integer.parseInt(line.substring(i + 1, j).trim());
			    String pdu = reader.readLine();
			    if(SmsUtil.isSMSMsgIn(pdu))
			        ll.add(new SMSMsgIn(pdu, memIndex));
			}

			reader.close();
			return ll;
		} catch (NumberFormatException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (Exception e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
//        Exception ex;
//        ex;
//        ex.printStackTrace();
        return null;
    }

    public boolean sendText(String phone, String text)
    {
        SMSMsgOut m = new SMSMsgOut(phone, text);
        String pdu = m.getPdu();
        return sendPduText(pdu);
    }

    public boolean sendPduText(String pdu)
    {
        //        JVM INSTR monitorenter ;
		String response;
		try {
			int size = SmsUtil.getSMSSize(pdu);
			Object obj = _SYNC_;
			String at_comm_send = _CharacterUtil.replaceSymbol("AT+CMGS=\"{1}\"\r", "\"{1}\"", "" + size);
			send(at_comm_send);
			for(; !dataAvailable(); Thread.sleep(10L));
			for(; dataAvailable(); skipBytes(1));
			pdu = pdu + (char)Integer.parseInt("1a", 16);
			send(pdu);
			response = getResponse();
			for(int i = 0; response.equals("") && i < 3; response = getResponse())
			{
			    Thread.sleep(500L);
			    i++;
			}
	        if(response.indexOf("OK\r") > -1)
	            return true;
	        
		} catch (NumberFormatException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (Exception e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}


//        false ;
//        obj;
//        JVM INSTR monitorexit ;
//        return;
//        Exception exception;
//        exception;
//        throw exception;
//        Exception ex;
//        ex;
//        ex.printStackTrace();
        return false;
    }

    public void setBaud(int baud)
    {
        this.baud = baud;
    }

    private static final int RECV_TIMEOUT = 3000;
    private static final int BUFFER_SIZE = 8192;
    private static final int DELAY_BETWEEN_CHARS = 5;
    private String port;
    private Object _SYNC_;
    private SerialPort serialPort;
    private InputStream inStream;
    private OutputStream outStream;
    private int baud;
    long timeStamp;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -