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

📄 cardproxy.java

📁 采用JAVA开发
💻 JAVA
字号:
package com.gctech.sms.util;

import com.gctech.util.LimitedSynchronizedInt;
import com.gctech.util.Tools;
import java.net.Socket;
import java.io.*;
import org.apache.log4j.Logger;
import EDU.oswego.cs.dl.util.concurrent.Sync;
import EDU.oswego.cs.dl.util.concurrent.Mutex;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import com.gctech.util.Startable;
import com.gctech.util.StartException;
import com.gctech.sms.SmsException;
import java.util.StringTokenizer;
import com.gctech.sms.app.SubService;
import com.gctech.sms.client.SmsProxy;



/**
 * 河南网关接口。
 * $Id: CardProxy.java,v 1.3 2004/06/22 08:13:35 wengjl Exp $
 * */
public class CardProxy implements Runnable{

  Socket socket = null;
  static final Logger logger = Logger.getLogger(CardProxy.class);
  private long lastAccessTime = System.currentTimeMillis();

  void doService(){
    try {
      while (socket.isConnected() && this.connected ) {
        byte[] head = new byte[60];
        int rt = in.read(head);
        if (rt != 60) {
          throw new IOException("读取包头错误:" + rt);
        }
        int effLen = Tools.byte2unsignedShort(head, 8);
        if (effLen < 0 || effLen > 2048) {
          throw new IOException("有效数据长度错误:" + effLen);
        }
        int funcCode = Tools.byte2unsignedShort(head, 32);
        logger.debug("receiver message "+ funcCode);
        this.lastAccessTime = System.currentTimeMillis();
        byte[] effData = new byte[effLen];
        int realEffLen = in.read(effData);
        if ( realEffLen != effLen ){
          throw new IOException("有效数据长度不符合:" + effLen+"vs"+
                                realEffLen);
        }
        if ( funcCode == FunctionCode.ACTIVE_TEST_RESP ){
          CardLogger.getInstance().logActiveTestResp(head);
          continue;
        }
        int status = Tools.byte2unsignedShort(head, 34);
        int seq = Tools.byte2unsignedShort(head, 4);
        //找到请求或回复类型
        Object obj = this.appServices.get(new Integer(funcCode));
        if ( obj == null ){
          logger.warn("找不到功能ID:" + funcCode);
          throw new IOException("找不到功能ID:" + funcCode);
        }else{
          SubService service = (SubService)obj;
          byte[] data = service.service(head, effData);
          out.write(data);
        }
//        Sync lock = null;
//        String msgId = null;
//        msgId = new String(effData, 0, 20);
        /*

        Object obj = this.lockPool.get(msgId);
        if ( obj == null ){
          logger.warn("不能找到消息锁:"+msgId);
        }else{
          lock = (Sync)obj;
          this.lockPool.put(msgId, resp);
          lock.release();
        }*/
      }
    }
    catch (IOException ex) {
      logger.error(ex, ex);
      this.connected = false;
    }
  }
  //读取消息
  public void run(){
    ActiveTester tester = new ActiveTester();
    Thread t = new Thread(tester, "ACTIVE_TESTER");
    t.start();
    while ( true ) {
      if ( connected ){
        doService();
      }else{
        while ( reconnect() != 0 ){
          try {
            Thread.sleep(2000L);
          }
          catch (InterruptedException ex) {
            logger.error(ex, ex);
          }
        }
      }
    }
  }
  private String destIp;
  private int destPort;
  int reconnect()   {
    try {
      return init(this.destIp, this.destPort, this.srcNodeId, this.destNodeId);
    }
    catch (SmsException ex) {
      logger.error(ex, ex);
      return -100;
    }
  }
  //static final int TIME_OUT = 10*1000;
  static final int SOCKET_TIME_OUT = 3*60*1000;
  static final int BUSINESS_TIME_OUT = 20000;


  public static void main(String[] args) {
    try {
      InputStream in = new BufferedInputStream(new FileInputStream("I:/smsd/test.txt"));
      int count = in.available();
      byte[] data = new byte[count];
      in.read(data);
      System.out.println(new String(data));
      String test = "test中文";

      byte[] utf81 = new String(test.getBytes(), "UTF8").getBytes("UTF8");
      String test2 = new String(utf81);
      System.out.println(test2);
      byte[] utf82 = new String(test.getBytes(), "UTF-8").getBytes("UTF-8");
      for ( int i = 0; i < utf81.length; i++ ){
        System.out.print(utf81[i]);
      }
      System.out.println();
      for ( int i = 0; i < utf82.length; i++ ){
        System.out.print(utf82[i]);
      }

    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  OutputStream out;
  InputStream in;
  boolean connected(){
    return this.connected;
  }
  synchronized void send(byte[] data)  {
    try {
      out.write(data);
    }
    catch (IOException ex) {
      logger.error(ex, ex);
      this.connected = false;
    }
    this.lastAccessTime = System.currentTimeMillis();
  }
  Map appServices;
  /**
   * @see init(String destIp, int destPort, int srcNodeId, int destNodeId)
   * */
  public int init(Properties props) throws SmsException{
    //载入服务
    StringTokenizer stk = new StringTokenizer(props.getProperty(
        "com.gctech.sms.util.CardProxy.services"), ",");
    for ( ; stk.hasMoreTokens(); ){
      String service = stk.nextToken();

      Integer serviceId = Integer.decode(props.getProperty(
          "com.gctech.sms.util.CardProxy.services." + service + ".seq"));
      String serviceName = props.getProperty(
          "com.gctech.sms.util.CardProxy.services." + service + ".class");
      try {
        appServices.put(serviceId, Class.forName(serviceName).newInstance());
        logger.info("注册服务 ID:" + serviceId + ",服务类名:" + serviceName
                    + " 成功。");
      }
      catch (Exception ex) {
        logger.info("注册服务 ID:" + serviceId + ",服务类名:" + serviceName
                    + " 失败。", ex);
      }
    }
    //设置与短信平台接口
    SmsProxy proxy = SmsProxy.getInstance();
    proxy.setHost(props.getProperty("com.gctech.sms.util.PlatformIp"));
    proxy.setPort((new Integer(props.getProperty("com.gctech.sms.util.PlatformPort"))).intValue());
    logger.info("设置与短信平台接口 port="+ props.getProperty("com.gctech.sms.util.PlatformPort") + " hostip="+props.getProperty("com.gctech.sms.util.PlatformIp"));
    String tmpDestIp = props.getProperty("com.gctech.sms.util.destIp");
    int tmpDestPort = Integer.parseInt(props.getProperty(
        "com.gctech.sms.util.destPort"));
    int tmpSrcNodeId = Integer.parseInt(props.getProperty(
        "com.gctech.sms.util.srcNodeId"));
    int tmpDestNodeId = Integer.parseInt(props.getProperty(
        "com.gctech.sms.util.destNodeId"));
    return init(tmpDestIp, tmpDestPort, tmpSrcNodeId, tmpDestNodeId);
  }
  /**
   * 初试化。
   * */
  public int init(String destIp, int destPort,
                   int srcNodeId, int destNodeId)
      throws SmsException{
//    this.lockPool.clear();
    this.srcNodeId = srcNodeId;
    this.destNodeId = destNodeId;
    this.destIp = destIp;
    this.destPort = destPort;
    //登录
    try {
      socket = new Socket(destIp, destPort);
      socket.setKeepAlive(true);
      socket.setSoTimeout(SOCKET_TIME_OUT);
      out = socket.getOutputStream();
      in = socket.getInputStream();
      byte[] data = new byte[60];
      this.envalop(data);
      //功能码,有效数据长度
      Tools.short2byte(FunctionCode.LOGIN, data, 32);
      //Tools.int2byte();
      send(data);
      byte[] loginResp = new byte[60];
      int length = in.read(loginResp);
      if ( length != 60 ){
        throw new SmsException("读取登录回复长度错误:"+length);
      }

      int loginFunc = Tools.byte2unsignedShort(loginResp, 32);
      if ( loginFunc != FunctionCode.LOGIN_RESP ){
        throw new SmsException("登录回复功能码错误:"+loginFunc);
      }
      this.lastAccessTime = System.currentTimeMillis();
      this.connected = true;
      return 0;
    }
    catch (IOException ex) {
      throw new SmsException(ex);
    }
  }
  LimitedSynchronizedInt seq;

  private CardProxy() {
    seq = new LimitedSynchronizedInt(0, 0, 0x010000);
    appServices = new HashMap();
//    lockPool = new HashMap();

  }
  static long TEST_INTERVAL = 1000L*10L;


  int envalop(byte[] data){
    //报文标志
    data[0] = (byte)0x99;
    data[1] = (byte)0x88;
    //版本
    data[3] = (byte)0x01;
    data[4] = (byte)0x00;
    //报文序号
    int cur = seq.increment();
    Tools.short2byte(cur, data, 4);
    //报文类型

    //源单位代码
    Tools.int2byte(this.srcNodeId, data, 14);
    //目的单位代码
    Tools.int2byte(this.destNodeId, data, 18);
    //业务类型
    return cur;
  }
  int srcNodeId;
  int destNodeId;
  boolean connected = false;
  void activeTest(){
    //logger.debug("test message!");
    if ( System.currentTimeMillis() - this.lastAccessTime
         > TEST_INTERVAL ){
      byte[] data = new byte[60];
      this.envalop(data);
      //功能码,有效数据长度
      Tools.short2byte(FunctionCode.ACTIVE_TEST, data, 32);
      send(data);
      CardLogger.getInstance().logActiveTest(data);
    }
  }



//  private Map lockPool;
  private static CardProxy singleton;
  public static CardProxy getInstance(){
    if ( singleton == null )
      singleton = new CardProxy();
    return singleton;
  }


  public class ActiveTester implements Runnable {
    public void run(){
      while ( true ){
        try {
          Thread.sleep(1000L);
          activeTest();
        }
        catch (InterruptedException ex) {
          logger.error(ex, ex);
        }
      }
    }
  }


}

⌨️ 快捷键说明

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