Flex amf3通訊協議實例

arthurcsh 12年前發布 | 89K 次閱讀 flex amf3 Flex開發

服務端:

import java.io.BufferedOutputStream;   
import java.io.BufferedReader;   
import java.io.BufferedWriter;   
import java.io.ByteArrayInputStream;   
import java.io.ByteArrayOutputStream;   
import java.io.DataInputStream;   
import java.io.DataOutputStream;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.io.InputStreamReader;   
import java.io.ObjectOutputStream;   
import java.io.OutputStream;   
import java.io.OutputStreamWriter;   
import java.net.ServerSocket;   
import java.net.Socket;   
import java.util.HashMap;   

import flex.messaging.io.SerializationContext;   
import flex.messaging.io.amf.Amf3Input;   
import flex.messaging.io.amf.Amf3Output;   

public class AmfServer   
{   
public static void main(String args[])   
{   
   SerializationContext serializationContext=new SerializationContext();   

   //序列化amf3對象   
   Amf3Output amfout=new Amf3Output(serializationContext);   

   //實現了一個輸出流,其中的數據被寫入一個 byte 數組。   
   ByteArrayOutputStream byteoutStream=new ByteArrayOutputStream();   

   //將byteoutStream產生的數組流導入到DataOutputStream流中   
   DataOutputStream dataoutstream=new DataOutputStream(byteoutStream);   

   //創建ServerSocket和Socket對象   
   ServerSocket serverSocekt;   
   Socket socket;   

   // 設置流的編碼格式為amf3   
   amfout.setOutputStream(dataoutstream);   

   //創建Map對象、Double對象數組   
   HashMap map=new HashMap();   
   map.put("Event", "人物移動");   
   map.put("user", "閃刀浪子");   
   map.put("x", 100);   
   map.put("y", 100);     

   try {   
    amfout.writeObject(map);//實際上是將map對象寫入到dataoutstream流中   
    dataoutstream.flush();//清空緩存   
   } catch (IOException e) {   
    e.printStackTrace();   
   }   

   //將ByteArrayOutputStream流中轉化成字節數組   
   byte[] messageBytes=byteoutStream.toByteArray();//amf3數據   

   OutputStreamWriter osw;//使用amf3格式將寫入流中的數據編碼成字節   
   BufferedWriter bwrite;//用來封裝OutputStreamWriter,以提高效率   

   try {   

    System.out.println("輸出數組長度"+messageBytes.length);      
    serverSocekt=new ServerSocket(1028);//開啟服務器進程      
    System.out.println("服務器已經啟動。。。。。。。");      
    socket=serverSocekt.accept();      
    if(socket.isConnected())   
    {   
     System.out.println(">>>>>>>>>>客戶端已連接");   
    }   
    //socket.   
    osw=new OutputStreamWriter(socket.getOutputStream());//將字符流轉化為字節流   
    bwrite=new BufferedWriter(osw);//封裝osw對象,提高寫入的效率   
    socket.getOutputStream().write(messageBytes);//向流中寫入二進制數據   
    socket.getOutputStream().flush();   
    socket.getOutputStream().close();   

   } catch (FileNotFoundException e) {   
      e.printStackTrace();   
   }   
   catch (IOException e) {   
      e.printStackTrace();   
   }   
}   
}  



客戶端:
var socket:Socket=new Socket();   
socket.addEventListener(Event.CLOSE, closeHandler);   
socket.addEventListener(Event.CONNECT, connectHandler);   
socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);   
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);   
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);   
socket.connect("localhost",1028);   
var obj:Object=new Object();   

addEventListener("recieved",recievedData);   
function recievedData(evt:Event)   
{   
switch (obj.Event) {   
   case "人物移動" :   
    trace("把玩家:"+obj.user+" 移動到"+obj.x+","+obj.y);   
    break;   
   case "人物換裝" :   
    trace("人物換裝");   
    break;   
   case "消息廣播" :   
    trace("系統信息");   
    break;   
   default :   
    break;   
}   

};   

function closeHandler(event:Event):void {   
trace("連接關閉");   
}   

function connectHandler(event:Event):void {   
trace("連接成功");   
}   

function ioErrorHandler(event:IOErrorEvent):void {   
trace("ioErrorHandler信息: " + event);   
}   

function securityErrorHandler(event:SecurityErrorEvent):void {   
trace("securityErrorHandler信息: " + event);   
}   

function socketDataHandler(event:ProgressEvent):void {   

trace("接收數據");  
obj=socket.readObject();   
this.dispatchEvent(new Event("recieved"));   
}  



壓縮的AMF數據通訊協議

服務端:
上篇文章介紹和如何在java中將數據封裝成flash可以直接讀取的amf格式,amf雖然已經“壓縮”過了(相對其他xml、json等,由于基于二進制而且比較少冗余數據,體積會小很多)。 
但是還可以進一步壓縮的,由于as3的bytearray支持compress和uncompress。所以我們可以在Java端將數據壓縮,然后在flash端讀取再解壓縮,這樣數據在傳輸過程中又會小很多。 
下面就介紹使用方法,基于前篇文章的范例: 

服務端: 
import java.io.BufferedWriter; 
import java.io.ByteArrayOutputStream; 
import java.io.DataOutputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.zip.Deflater; 
import java.util.zip.DeflaterOutputStream; 
import java.util.zip.Inflater; 
import java.util.zip.ZipFile; 
import java.util.zip.ZipInputStream; 

import flex.messaging.io.SerializationContext; 
import flex.messaging.io.amf.Amf3Output; 
import flex.messaging.log.Log; 
import flex.messaging.messages.Message; 


public class Test { 

/** 
* @param args 
*/ 
public static void main(String[] args) 
{ 
SerializationContext serializationContext=new SerializationContext(); 
Amf3Output amfOut = new Amf3Output(serializationContext); 
    ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
    DataOutputStream dataOutStream = new DataOutputStream(outStream); 
    amfOut.setOutputStream(dataOutStream); 

    HashMap<String, Object> map=new HashMap<String, Object>(); 
    Double[] arr=new Double[10000]; 
    for(int index=0;index<10000;index++) 
    { 
     arr[index]=Math.random(); 
    } 
    map.put("arr", arr); 
    map.put("name", "weni"); 
    map.put("age", "27"); 
    try 
    { 
amfOut.writeObject(map); 
dataOutStream.flush(); 
} catch (IOException e) 
{ 
e.printStackTrace(); 
} 

    byte[] messageBytes = outStream.toByteArray(); 



    try  
    {  
      FileOutputStream  os;  
      OutputStreamWriter  ow;  
      BufferedWriter  out;  
      os  =  new  FileOutputStream("D://test.txt");  
      ow  =  new  OutputStreamWriter(os);  
      out  =  new  BufferedWriter(ow);  
      os.write(messageBytes); 
      os.flush(); 
      os.close(); 
      messageBytes=compressBytes(messageBytes); //將數據進行壓縮 
      System.out.println("OK"); 
}catch(Exception  e)  
{ 
System.out.println("error  :"  +  e);                       
} 
} 

private static int cachesize = 1024; 
private static Inflater decompresser = new Inflater(); 
private static Deflater compresser = new Deflater(); 
public static byte[] compressBytes(byte input[]) 
{ 
compresser.reset(); 
compresser.setInput(input); 
compresser.finish(); 
byte output[] = new byte[0]; 
ByteArrayOutputStream o = new ByteArrayOutputStream(input.length); 
try 
{ 
byte[] buf = new byte[cachesize]; 
int got; 
while (!compresser.finished()) 
{ 
got = compresser.deflate(buf); 
o.write(buf, 0, got); 
} 
output = o.toByteArray(); 
} finally 
{ 
try 
{ 
o.close(); 
} catch (IOException e) 
{ 
e.printStackTrace(); 
} 
} 
return output; 
} 
public static byte[] decompressBytes(byte input[]) 
{ 
byte output[] = new byte[0]; 
decompresser.reset(); 
decompresser.setInput(input); 
ByteArrayOutputStream o = new ByteArrayOutputStream(input.length); 
try 
{ 
byte[] buf = new byte[cachesize]; 

int got; 
while (!decompresser.finished()) 
{ 
got = decompresser.inflate(buf); 
o.write(buf, 0, got); 
} 
output = o.toByteArray(); 
}catch(Exception e) 
{ 
e.printStackTrace(); 
}finally 
{ 
try 
{ 
o.close(); 
} catch (IOException e) 
{ 
e.printStackTrace(); 
} 
} 
return output; 
} 
} 



客戶端:
public class AMF3Test extends Sprite 
{ 
private var loader:URLLoader; 
public function AMF3Test() 
{ 
loader=new URLLoader(); 
loader.load(new URLRequest("D://test5.txt")); 
loader.addEventListener(Event.COMPLETE,onComplete); 
loader.dataFormat=URLLoaderDataFormat.BINARY; 
} 

private function onComplete(evt:Event):void 
{ 
var start:Number=getTimer(); 
var byte:ByteArray=loader.data as ByteArray; 
byte.uncompress() //將數據進行解壓縮 
var obj:Object=byte.readObject(); 
var end:Number=getTimer(); 
trace("耗時:"+(end-start)+"毫秒") 
trace(obj.name,obj.age,obj.arr.length) 
} 
} 
 本文由用戶 arthurcsh 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!