`

Erlang与Flash的Socket通讯-01

    博客分类:
  • AS3
阅读更多

晚上做了下实验,Erlang端用{packet,2}格式,Flash端使用writeUTF和readUTF函数,正好格式一致,不需要自己解析两个字节长度信息。


Erlang端的代码:
-module(server).
-export([start/1, server_proc/1]).

start (Port) ->
    {ok, Sock} = gen_tcp:listen(Port, [binary, {packet, 2}, {active, false}]),

    server_loop(Sock).

server_loop (LSock) ->
    {ok, Sock} = gen_tcp:accept(LSock),

    spawn(?MODULE, server_proc, [Sock]),

    server_loop(LSock).

server_proc (Sock) ->
    Request = case gen_tcp:recv(Sock, 0) of
        {ok, ReqBin}    ->
            binary_to_list(ReqBin);
        {error, closed} ->
            io:format("Client closed~n"), exit(closed);
        {error, Reason} ->
            io:format("Error: ~s~n", Reason), exit(Reason)
    end,

    io:format("Received: ~p~n", [Request]),

    Response = "Done!",

    gen_tcp:send(Sock, Response),

    server_proc(Sock).

Flash端实验代码:
package
{
    import flash.net.Socket;
    import flash.display.Sprite;
    import flash.events.ProgressEvent;

    public class Main extends Sprite
    {
        private var sock:Socket;

        public function Main ()
        {
            sock = new Socket();

            sock.addEventListener(ProgressEvent.SOCKET_DATA, function (event:ProgressEvent):void
            {
                trace(sock.readUTF());
                sock.close();
            });

            sock.connect("localhost", 10086);

            sock.writeUTF("Hello World!");

            sock.flush();
        }
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics