今天下午写了一个简单 client / server通信例子。
前端:flash AS3
后台:Erlang
package { import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; public class MySocket extends Sprite { private static const port:int = 8080; private static const ip:String = "127.0.0.1"; private var socket:Socket; public function MySocket() { socket = new Socket(); socket.connect(ip,port); 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); } private function closeHandler(e:Event):void { trace("connect close"); } private function connectHandler(e:Event):void { trace("connect ok"); //test -> send to socket socket.writeInt(6); socket.flush(); } private function ioErrorHandler(e:IOErrorEvent):void { trace(e.errorID); } private function securityErrorHandler(e:SecurityErrorEvent):void { } private function socketDataHandler(e:ProgressEvent):void { var msg:int = socket.readInt(); trace(msg.toString()); } } }
%%Author:Lee %%socket example -module(my_socket). -compile(export_all). -define(TCP_OPTION,[ binary, {packet,0}, {active,false}, {reuseaddr, true} ]). -define(POLICY_PORT,8080). %%监听端口 %%gen_tcp表用TCP连接 %%binary表二进制流方式 %%packet,2:表包头长度2字节 %%reuseaddr, true:表多个实例可重用同一端口 %% {active,true} 创建一个主动套字节(非阻塞) %% {active,false} 创建一个被动套字节(阻塞),如果为false表必须手工处理阻塞,否则阻塞在此处无法收听,当前我无法处理 %%{active, once} 创建一个一次性被动套字节(阻塞),只收听一次后堵塞,必须调用inet:setopts(Socket, [{active, once}]),后才可收听下一条 %% {active,once} 创建一个主动套字节仅接收一条消息,如想接收下一条必须再次激活(半阻塞) start()-> case gen_tcp:listen(?POLICY_PORT,?TCP_OPTION) of {ok,LSock}-> io:format("success listen~n",[]), accept(LSock); _-> io:format("unknow~n") end. accept(LSock) -> case gen_tcp:accept(LSock) of {ok, CSock} -> spawn(?MODULE,loop_accept,[CSock]); {error,Reason} -> Reason end, accept(LSock). loop_accept(LSock)-> case gen_tcp:recv(LSock,0) of {ok,Data} -> io:format("receive data~p~n",[Data]), gen_tcp:send(LSock,Data), loop_accept(LSock); _-> error end. %%gen_tcp:close(LSock).
可以正常的通信, 打算明天用 erlang的 gen_server模拟一个server端...就到这吧..