转自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
暗夜教父 阅读(884)
评论(0) 编辑 收藏 引用 所属分类:
erlang