免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1322 | 回复: 0
打印 上一主题 下一主题

Client [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-06-24 17:25 |只看该作者 |倒序浏览
//CommClient.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.ResultSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class CommClient extends Thread
{
private final static int headLen=37;
    private InetAddress ip=null;   
    private Socket s=null;  
    private Socket res=null;
    private InputStream is=null;   
    private OutputStream os=null;
     
   public CommClient()
   {   
     try
     {   
      ip=InetAddress.getLocalHost();   
      s=new Socket(ip,2227);  
      res=new Socket(ip,2226);
      is=s.getInputStream();
      os=s.getOutputStream();
     }   
     catch(Exception ex)
     {   
         ex.printStackTrace();   
         System.err.println("public Client.");   
     }   
   }   
     
//将File对象转换为字节数组
   public static byte[] getBytesFromFile(File f)
   {
         if (f == null)
         {
             return null;
         }
         try
         {
             FileInputStream stream = new FileInputStream(f);
             ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
             byte[] b = new byte[1000];
             int n;
             while ((n = stream.read(b)) != -1)
                 out.write(b, 0, n);
             stream.close();
             out.close();
             return out.toByteArray();
         }
         catch(IOException e)
         {
          e.printStackTrace();
         }
         return null;
     }
   
   /**
    * @param orgInfo :待封装的原始信息(包括:文件名和图像数据)
    * @param flag  :数据包封装格式类型
    * 1 文本格式封装  2 图像格式封装  3 视频格式封装
    * @return
    */
   public byte[] generateImgPacket(byte[] orgInfo,String bsID,
     short servType,int pacLength)  
   {
    byte [] dataPacket=new byte[orgInfo.length +37];
   
    byte [] bsId = bsID.getBytes();
   
     
    //图像数据包
  byte [] bbsID=new byte[30];
  System.arraycopy(bsId, 0, bbsID, 0, bsId.length);
//  System.arraycopy(bsID.getBytes(), 0, bbsID, 0, bsID.getBytes().length);
  byte [] bservType=ByteConvert.ShortToByte(servType);//字节数组长度为2
  System.out.println("bservType length:"+bservType.length);
  byte [] bpacLength=ByteConvert.IntToByte(pacLength);//字节数组长度为4
  System.arraycopy(bbsID, 0, dataPacket, 0, bbsID.length);
  System.arraycopy(bservType, 0, dataPacket, 30, bservType.length);
  System.arraycopy(bpacLength, 0, dataPacket, 32, bpacLength.length);
  dataPacket[36]=(byte)2;
  System.arraycopy(orgInfo, 0, dataPacket, 37, orgInfo.length);
  //dataPacket=generateImagePacket(orgInfo);   
     return dataPacket;
   }
   
   public byte [] generateTextPacket(String baseID,short servType,byte dataFlag)
   {
    byte [] textPacket=null;
    //int sType=(int)servType;
    int pacLen=0;
   
    String textInfo=null;
    switch(servType)
    {//服务类型
    case 1:
     textInfo=new String(""+
         "A1234四川省XX县XX镇XX路X段XX号"+
"B1234四川省XX市XX乡XX村XX组");//文本信息
     
     
     
     break;
    case 2:
     
     break;
     
    case 3:
     
     break;
    case 4:
     
     break;
    case 5:
     
     break;
     
    case 6:
     
     break;
    case 7:
     
     break;
    case 8:
     
     break;
     
    case 9:
     
     break;
    case 10:
     
     break;
    case 11:
     
     break;
     
    case 12:
     
     break;
    case 13:
     
     break;
     
    case 14:
     textInfo=new String(""+
         "862");//文本信息
     byte [] btextInfo=textInfo.getBytes();
     textPacket=new DataPacket(baseID,servType,btextInfo.length+headLen,dataFlag,btextInfo).getBytes();
//    byte [] bReceivePacket=receivePacket(InputStream is);
     break;
    default:
     
     break;
    }
   
//    byte [] btextInfo=textInfo.getBytes();
//    pacLen=btextInfo.length+37;
//    byte [] bpacLen=ByteConvert.IntToByte(pacLen);//数据包长度
//   
//    textPacket=new byte[pacLen];
//    System.arraycopy(btextInfo, 0, textPacket, 37, btextInfo.length);
//    System.arraycopy(bpacLen, 0, btextInfo, 32, bpacLen.length);
   
    return textPacket;
   }
   
   /**
    * 图像数据包封装
    */
  // public byte[] generateImagePacket(byte [] imgInfo,
   public void run()
   {  
    //身份认证
    System.out.println("This is Client");
    byte [] csKey=new byte[100];
    byte [] buf1=new byte[100];
   
    try
     {
//  is=s.getInputStream();
//  is=s.getInputStream();
//  is=s.getInputStream();
//  os=s.getOutputStream();
  
  //身份验证
  int len = is.read(buf1);// 从输入流中读取数据到buf
  System.out.println(new String(buf1,0,len));//提示输入私钥
  System.out.print(">>");
  System.in.read(csKey);
  os.write(csKey);
  
     len=is.read(buf1);
     if(buf1[0]==1)
      System.out.println("Connect successfully!");
     else
     {
      System.out.println("Invalid key");
      System.exit(0);
     }
     
   
     /*
      * 确定参数:
      *    发送基站ID:baseID
      *    服务类型号:servType
      *    数据标志:dataFlag
      */
      String baseID="公安部第三研究所车辆监控基站";
//      short servType=(short)20;//传送图片服务号
      short servType=(short)14;//传送图片服务号
      byte dataFlag=(byte)1;//数据标志
      
      byte [] dataPacket=null;
     
     //根据服务类型进行数据包封装
      switch(servType)
      {
      case 14://文本
      
       dataPacket=generateTextPacket(baseID,servType,dataFlag);  
       sendPacket(dataPacket,os);
     //  os.flush();
      
       System.out.println("is socket closed? "+s.isClosed());
      
       is=res.getInputStream();
       byte [] bu=new byte[1024];
       int len1=is.read(bu);//输入流中无数据可读,阻塞。。
      
      
      
      
      // is=s.getInputStream();//socket已经关闭???
      //byte [] bRecvPacket=receivePacket(is);//接收服务器返回的查询结果
      // parsePacket(bRecvPacket);
       break;
      case 20://图像服务号
      //以流形式读取图片
      
      //提供文件对话框选择要发送的图片??
       String filePath=new String("C:\\");//图片目录
       String filename=new String("20090622.jpg");//图片文件名
       File f=new File(filePath+filename);
       //图像数据格式封装
       byte[] imgData=getBytesFromFile(f);
          byte[] bPath=filename.getBytes();
       byte[] bfileName=new byte[51];
       System.arraycopy(bPath, 0, bfileName, 0, bPath.length);
       byte[] bImg=new byte[imgData.length+51];//加上文件名
       System.arraycopy(bfileName, 0, bImg, 0, bfileName.length);
       System.arraycopy(imgData, 0, bImg, 51, imgData.length);
       dataPacket=generateImgPacket(bImg,baseID,servType,bImg.length+37);
      
       sendPacket(dataPacket,os);
       break;
      case 3://视频
      
       break;
      default:
       break;
      
      }   
      
//      byte [] dataPacket=null;
      //以流形式发送封装好的数据包
//      System.out.println(dataPacket.length);
////      System.out.println("图像文件最后字节:"+imagePacket[88+24853]);
//      for(int i=0;ib3      
//      DataInputStream dis=new DataInputStream(bais);
//      
//      
//      //加密    cypheredPacket()
//      
//      
//      //组装 assemblyPacket()
//      
//
//    //创建网络输出流并提供数据包装器
//      OutputStream ops=new DataOutputStream(new BufferedOutputStream(os));
//         //创建文件读取缓冲区
//         byte[] buf=new byte[1024];
//         int num=dis.read(buf);
//         while(num!=(-1))
//         {//是否读完文件
//              ops.write(buf,0,num);//把文件数据写出网络缓冲区
//              ops.flush();//刷新缓冲区把数据写往客户端
//              num=dis.read(buf);//继续从文件中读取数据
//         }
//         ops.close();
    }   
    catch(Exception ex)
    {   
        ex.printStackTrace();   
    }   
   
   
}
  
   
   /**
    * function:capsulate the byte array and write it
    *        to os getting from Socket OutputStream
    * @param bqRest
    * @param os
    */
   public void sendPacket(byte [] bDataPacket,OutputStream os)
   {
       try
       {
        
     ByteArrayInputStream bas=new ByteArrayInputStream(bDataPacket);//imagePacket-->b3      
        DataInputStream ds=new DataInputStream(bas);
         
         
         //加密    cypheredPacket()
         
         
         //组装 assemblyPacket()
         
   
         //创建网络输出流并提供数据包装器
        OutputStream ops=new DataOutputStream(new BufferedOutputStream(os));
           //创建文件读取缓冲区
           byte[] buf=new byte[1024];
           int num=ds.read(buf);
           while(num!=(-1))
           {//是否读完文件
              ops.write(buf,0,num);//把文件数据写出网络缓冲区
              ops.flush();//刷新缓冲区把数据写往客户端
              num=ds.read(buf);//继续从文件中读取数据
           }
         //  os.flush();
          ops.close();  //关闭输出流,同时关闭socket
         //  os=s.getOutputStream();
           ds.close();  
       }
       catch(Exception e)
       {
        e.printStackTrace();
       }
   }
  /**
   * function:read DataPacket from InputStream to byte array
   * @param in
   * @return
   */
  public byte [] receivePacket(InputStream in) throws Exception
  {
   byte [] buf=new byte[2];
   int len=in.read(buf);
   System.out.println(new String(buf,0,len));
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
       transform(in,baos);
       byte [] bDataPacket=baos.toByteArray();
       System.out.println(new String(bDataPacket,0,bDataPacket.length));
       return bDataPacket;
  }
  
   /**
    * function:
    *   transform InputStream to OutputStream
    * @param in
    * @param out
    */
   public void transform(InputStream in,OutputStream out)
   {
   
    int c=0;
    try
    {
      while((c=in.read())!=-1)
      {
       out.write(c);
      }
    }
    catch(Exception e)
    {
     e.printStackTrace();
    }
   }
   
   
   
   public void parsePacket(byte [] datapacket)
   {
    //公共数据包前缀解析
    byte [] baseId=new byte[30];
    byte [] servType=new byte[2];
    byte [] packetLen=new byte[4];
    byte flag;
    System.arraycopy(datapacket, 0, baseId, 0, baseId.length);
    System.arraycopy(datapacket, 30, servType, 0, servType.length);
    System.arraycopy(datapacket, 32, packetLen, 0, packetLen.length);
    flag=datapacket[37];
    System.out.println("The connection is from basestation:"+
      new String(baseId,0,baseId.length));
    int servId=(int)ByteConvert.ByteToShort(servType);
   
    byte [] bxml=null;
    //处理不同服务请求
    switch(servId)
    {
    case 1:
     bxml=new byte[datapacket.length-37];
     System.arraycopy(datapacket, 37, bxml, 0, bxml.length);
     try
     {
      ByteArrayInputStream bais=new ByteArrayInputStream(bxml);
         DataInputStream dis=new DataInputStream(bais);
       //  File f=new File("data_10k.xml");
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builder=factory.newDocumentBuilder();
        // FileInputStream fis=new FileInputStream(f);
        // DataInputStream dis=new DataInputStream(fis);
         Document doc = builder.parse(dis);
         NodeList nl = doc.getElementsByTagName("VALUE");
         for (int i=0;i"+
           "col[0]col[1]col[2]>"+
           "col[3]col[4]col[5]col[6]"+
           "col[7]col[8]"+
           "");
      byte [] bqRest = strPacket.getBytes();
//      String strPacket=new String(bqRest,0,bqRest.length);
     //DataPacket(String baseID,short servType,int pacLen,byte flag,byte [] bData)
     byte [] bqRestPacket=new DataPacket(strPacket,(short)15,bqRest.length+headLen,(byte)1,bqRest).getBytes();
      sendPacket(bqRestPacket,os);//将查询结果返回给客户端
      
     //关闭数据库连接
     dbc.close();
     rs.close();
     
     
//         for (int i=0;i
   }
   
public static void main(String[] args) throws Exception
{   
  new CommClient().start();  
}
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93928/showart_1976409.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP