java flash tcp字节流通信(四)-flash as3 粘包/半包处理器(数据缓存)

来源:互联网 发布:淘宝乔丹六折是正品? 编辑:程序博客网 时间:2024/06/05 03:25

1.重写socket类

package com.net.tcp
{
 
 import flash.net.Socket;
 
 public class NetSocket extends Socket
 {
  public function NetSocket(host:String=null, port:int=0)
  {
   super(host, port);
  }
  
  public function read(cache:DataCache):void{
   this.readBytes(cache, cache.position, this.bytesAvailable);
  }
  
  public function writePack(pack:DataPack):void{
   this.writeHead(pack.head);
   this.writeContent(pack.content);
  }
  
  private function writeHead(head:DataHead):void{
   this.writeUnsignedInt(head.len);
  }
  
  private function writeContent(content:DataContent):void{
   this.writeBytes(content, 0, content.bytesAvailable);
  }
 }
}

 

2.定义数据缓存类(粘包/半包处理器)

package com.net.tcp
{
 
 import flash.utils.ByteArray;

 /**
  *
  * 通信数据缓存(未完整数据)
  *
  **/
 public class DataCache extends ByteArray
 {
  
  public function DataCache()
  {
   super();
  }
  
  public function readDataPack():DataPack{
   this.begin();
   var pack:DataPack = null;
   if(this.bytesAvailable >= DataHead.DATA_HEAD_LEN){
    var head:DataHead = readDataHead();
    var content:DataContent = readDataContent(head);
    if(content != null){
     this.end(true);
     pack = new DataPack(content, head);
    }else{
     this.end();
    }
   }else{
    this.end();
   }
   return pack;
  }
  
  private function readDataHead():DataHead{
   var head:DataHead = new DataHead();
   head.len = this.readUnsignedInt();
   return head;
  }
  
  private function readDataContent(head:DataHead):DataContent{
   if(head.len > this.bytesAvailable){
    return null;
   }
   var content:DataContent = new DataContent();
   this.readBytes(content, 0, head.len);
   content.rewind();
   return content;
  }
  
  /**
   * 清除缓存所有内容
   **/
  public function reset():void{
   this.position = 0;
   this.length = 0;
  }
  
  /**
   * 定位缓存初始位置(begin)
   **/
  public function begin():void{
   this.position = 0;
  }
  
  /**
   * 定位缓存结束位置(end)
   * @sign 为true,丢弃已经读过的数据
   **/
  public function end(sign:Boolean = false):void{
   if(sign){
    if(this.position != 0){
     if(this.bytesAvailable == 0){
      this.reset();
     }else{
      var cache:DataCache = new DataCache();
      this.readBytes(cache, 0, this.bytesAvailable);
      cache.begin();
      this.reset();
      this.writeBytes(cache, 0, cache.bytesAvailable);
     }
    }
   }else{
    this.position = this.length;
   }
  }
 }
}

 

原创粉丝点击