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

📄 tcpservice.java

📁 用java进行socket 通信算法实现
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.util.*;

import org.jdom.*;
import org.jdom.input.*;

public class TcpService
{
  private static String fileName="e:\\wht\\wht_post.xml";
  private static long fileStamp=0;
  private static Element tcpConfig;
  private static Element fieldConfig;
  private static List txnConfig;
  private static Socket sc=new Socket();
  public TcpService() {
  }
  private static void  init() throws Exception
  {
    File xmlfile=new File(fileName);
    long fStamp = xmlfile.lastModified();
    if (fStamp != fileStamp)
      fileStamp = fStamp;
    SAXBuilder sab = new SAXBuilder();
    Document xmlDoc = sab.build(new FileInputStream(xmlfile));
    Element root = xmlDoc.getRootElement(); //先得到根元素
    tcpConfig  = root.getChild("tcp-config");
    fieldConfig  = root.getChild("mapping-field-def");
    txnConfig  = root.getChildren("mapping-txncode");
  }
  static
  {
    try
    {
      init();
    }catch(Exception e)
    {
      throw new RuntimeException("init fail "+e);
    }
  }
  private static boolean isChangedFile()
  {
    File xmlfile=new File(fileName);
    long fStamp = xmlfile.lastModified();
    if (fStamp != fileStamp)
      return true;

    return false;
  }
  public static void send(HashMap txnReq,HashMap txnRes) throws Exception
  {

    try
    {
     if(isChangedFile())
       init();
      InputStream in;
       OutputStream out;
       String sendStr="";
      String IP="";
      int port=9001;
      int timeout=60;
      List tcpConf=tcpConfig.getChildren();
      for(int i=0;i<tcpConf.size();i++)
      {
        Element application=(Element)tcpConf.get(i);
        List attr=application.getAttributes();
         Attribute att=(Attribute)attr.get(0);
         String attName=att.getValue().toLowerCase();
          if(attName.equals("ip"))
            IP=((Attribute)attr.get(1)).getValue();
          else if(attName.equals("port"))
            port=Integer.parseInt(((Attribute)attr.get(1)).getValue());
          else if(attName.equals("timeout"))
           timeout=Integer.parseInt(((Attribute)attr.get(1)).getValue());
       }
     System.out.println("IP:"+IP+"port:"+port+"timeout:"+timeout);
  //     InetSocketAddress sa = new InetSocketAddress(IP, port);
    //  sc.setSoTimeout(timeout * 1000);
      //sc.connect(sa, timeout * 1000);
      //out = sc.getOutputStream();
      sendStr=getFormatSend(txnReq);
    System.out.println("sendStr:"+sendStr);
    byte[] tb=sendStr.getBytes();
    System.out.println("byte len:"+tb.length);
    txnRes=getFormatReceive((String)txnReq.get("TransCode"),tb);
    }
    catch(Exception e){
        }
}
  public static String getFormatStr(String source,List Attr)
  {
       int len=0;
      boolean fill=false;
      String fillChar="0";
      String  fillPos="before";
      String defaultValue="";
      String rtnSource="";
      String tmpSource="";
      Attribute att=null;
      String attName="";
      tmpSource=source;
      for(int i=0;i<Attr.size();i++)
      {
        att=(Attribute)Attr.get(i);
        attName=att.getName();
        if(attName.equals("len"))
        {
          len=Integer.parseInt(att.getValue());
        }
        else if(attName.equals("fill"))
        {
         if(att.getValue().toLowerCase().equals("true"))
           fill=true;
       }
       else if(attName.equals("fillchar"))
       {
        fillChar=att.getValue();
       }
       else if(attName.equals("fillpos"))
      {
        if(att.getValue().toLowerCase().equals("last"))
          fillPos="lase";
      }
      else if(attName.equals("defaultValue"))
      {
        defaultValue = att.getValue();
      }
    }
    if(tmpSource==null || tmpSource.length()<=0)
       tmpSource=defaultValue;
    if(tmpSource.length()>=len)
      return tmpSource.substring(0,len);
    byte[] fills=new byte[len-tmpSource.length()];
    Arrays.fill(fills,fillChar.getBytes()[0]);
    if(fillPos.equals("last"))
      return tmpSource+new String(fills);
    else
      return new String(fills)+tmpSource;
  }
  private static List getAttrList(List Attr)
  {
    if(Attr.size()>1)
      return Attr;
    Attribute att=(Attribute)Attr.get(0);
    String attName=att.getValue();
    List commField=fieldConfig.getChildren();
    Element ef=null;
    List fAttr=null;

    if(commField!=null &&commField.size()>0)
    {
      for(int i=0;i<commField.size();i++)
      {
           ef=(Element)commField.get(i);
           fAttr=ef.getAttributes();
           if(((Attribute)fAttr.get(0)).getValue().equals(attName))
             return fAttr;
      }
    }
    return Attr;
  }
  private static String getFormatSend(HashMap mapReq)
  {
    String strSend="";
    String txnCode=(String)mapReq.get("TransCode");
    Element em=null;
    String strName="";
    String strV="";
    for(int i=0;i<txnConfig.size();i++)
    {
      em=(Element)txnConfig.get(i);
      Attribute attr=em.getAttribute("name");
      if(attr.getValue().equals(txnCode))
         break;
    }
   List subCh=em.getChildren();
   for(int i=0;i<subCh.size();i++)
   {
     em=(Element)subCh.get(i);
     Attribute attr=em.getAttribute("name");
     if(attr.getValue().equals(txnCode+"Req"))
        break;
    }
    subCh=em.getChildren();
    for(int i=0;i<subCh.size();i++)
   {
     em=(Element)subCh.get(i);
     Attribute attr=em.getAttribute("name");
     strName=attr.getValue();
     strV=(String)mapReq.get(strName);
     strSend+=getFormatStr(strV,getAttrList(em.getAttributes()));
    }
   return strSend;
  }

  private static HashMap getFormatReceive(String TxnCode,byte[] rcvdata)
{
  String txnCode=TxnCode;
  Element em=null;
  String strName="";
  String strV="";
  String strLen="";
  int defaultSize=1;
  int tmpSize=0;
  int currSize=0;
  byte[] tmpBytes;
  HashMap hashFormat=new HashMap(10);
  Attribute attr;
  for(int i=0;i<txnConfig.size();i++)
  {
    em=(Element)txnConfig.get(i);
    attr=em.getAttribute("name");
    if(attr.getValue().equals(txnCode))
       break;
  }
 List subCh=em.getChildren();
 for(int i=0;i<subCh.size();i++)
 {
   em=(Element)subCh.get(i);
    attr=em.getAttribute("name");
   if(attr.getValue().equals(txnCode+"Res"))
      break;
  }
  subCh=em.getChildren();
  for(int i=0;i<subCh.size();i++)
 {
   em=(Element)subCh.get(i);
   attr=em.getAttribute("name");
   strName=attr.getValue();
   strLen=getFieldLen(em);
   try
   {
     tmpSize=Integer.parseInt(strLen);
   }catch(Exception e)
   {
      return null;
   }
   if(tmpSize<=0)
     return null;
   strV=new String(rcvdata,currSize,tmpSize);
    System.out.println("strName:"+strName+"  value:"+strV);
    hashFormat.put(strName,strV);
    currSize+=tmpSize;
   }
 return hashFormat;
}

  /**
   * getFullAttributes
   *
   * @param em Element
   * @return Element
   */
  private static String getFieldLen(Element em) {
    Element rtnEm;
    List  lAttr;
    Attribute attr;
    String attrLen="";
     attr=em.getAttribute("len");
     if(attr==null)
     {
       attr=em.getAttribute("name");
       String  attrName=attr.getValue();
       List commField=fieldConfig.getChildren();
       Element ef=null;
       List fAttr=null;
       if(commField!=null &&commField.size()>0)
       {
         for(int i=0;i<commField.size();i++)
         {
              ef=(Element)commField.get(i);
             attr=ef.getAttribute("name");
             if(attr.getValue().equalsIgnoreCase(attrName))
             {
                attr=ef.getAttribute("len");
                return attr.getValue();
             }

         }
       }

     }
     else
     {
       attrLen=attr.getValue();
     }

    return attrLen;
  }

  public static void main(String[] argv)
  throws Exception
  {
                  HashMap hashReq=new HashMap(9);
                  HashMap hashRst=new HashMap(10);
                  hashReq.put("TransCode","TP001");
                  hashReq.put("ReqSeqNo","1111111");
                  hashReq.put("ReqData1", "2222222");
                  hashReq.put("ReqData2", "3333333");
                  hashReq.put("ReqData3", "4444444");
                  hashReq.put("ReqData4", "5555555");
                  hashReq.put("RspCode", "66666666");
                  hashReq.put("MacCode", "7777777");
                  hashReq.put("Rsvd", "888888");
                  send(hashReq,hashRst);

        }
}

⌨️ 快捷键说明

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