轉自http://www.javaeye.com/topic/401041
學erlang有一段時間了,現在在維護一套webim系統
并打算擴展成 webgame 的服務程序
在沒有使用包協議的時候,遇到好多粘包問題,實在惱火
查閱了相關資料:
Flash Socket 的 writeUTF() 會自動增加包頭長度的協議,剛好對應了
Erlang的Socket選項 {packet,2}
這使得兩者的通信非常完美,再也不用擔心粘包什么的問題了
下面是我寫的一個Flash Socket 接口:SocketBridge.as

package
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.Socket;
import flash.utils.*;
import flash.external.ExternalInterface;
import flash.system.*;

public class SocketBridge extends Sprite
{
Socket.prototype.timeout =3000;
private var socket:Socket;
public function SocketBridge()

{
socket = new Socket();
socket.addEventListener( Event.CONNECT, onConnect );
socket.addEventListener( ProgressEvent.SOCKET_DATA, onDataRecevice);
socket.addEventListener( Event.CLOSE, onClose);
socket.addEventListener( IOErrorEvent.IO_ERROR, onError);
if(ExternalInterface.available)

{
ExternalInterface.addCallback("socket_connect",socket_connect);
ExternalInterface.addCallback("socket_send",socket_send);
ExternalInterface.addCallback("load_policy",load_policy);
}
}
public function onError(e):void

{
ExternalInterface.call("sb_onerror",e.text);
socket.close();
}
public function load_policy(host:String,port):void

{
Security.loadPolicyFile("xmlsocket://"+host+":"+port);
}
public function socket_connect(host:String,port):void

{

try
{
socket.connect(host,port);

}catch(e)
{
ExternalInterface.call("sb_onerror",e.text);
}
}
public function socket_send(msg:String)

{
socket.writeUTF(msg);
socket.flush();
}
private function onConnect(event:Event):void

{
ExternalInterface.call("sb_onconnect",true);
}
private function onClose(event:Event):void

{
socket.close();
ExternalInterface.call("sb_onclose",true);
}
private function onDataRecevice( eventrogressEvent ):void

{
var sdata:String;

while(socket.bytesAvailable)
{
sdata = socket.readUTF();
ExternalInterface.call("sb_ondata",sdata);
}
}
}
}

posted on 2009-09-18 12:40
暗夜教父 閱讀(890)
評論(0) 編輯 收藏 引用 所屬分類:
erlang