Erlang和ActionScript3的Socket通讯

server.erl
-module(server).
-export([start/0,start/1,process/1]).
-define(defPort, 8888).

start() -> start(?defPort).

start(Port) ->
  case gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}]) of
    {ok, LSock} -> server_loop(LSock);
    {error, Reason} -> exit({Port,Reason})
  end.

%% main server loop - wait for next connection, spawn child to process it
server_loop(LSock) ->
  case gen_tcp:accept(LSock) of
    {ok, Sock} ->
      spawn(?MODULE,process,[Sock]),
      server_loop(LSock);
    {error, Reason} ->
      exit({accept,Reason})
  end.

%% process current connection
process(Sock) ->
  Req = do_recv(Sock),
  io:format("~p~n", [Req]),
  Resp = "Hello, " ++ Req ++ "!",
  do_send(Sock,Resp),
  gen_tcp:close(Sock).

%% send a line of text to the socket
do_send(Sock,Msg) ->
  case gen_tcp:send(Sock, Msg) of
    ok -> ok;
    {error, Reason} -> exit(Reason)
  end.

%% receive data from the socket
do_recv(Sock) ->
  case gen_tcp:recv(Sock, 0) of
    {ok, Bin} -> binary_to_list(Bin);
    {error, closed} -> exit(closed);
    {error, Reason} -> exit(Reason)
  end.


Client.as
package {
	import flash.display.Sprite;
	import flash.events.*;
	import flash.net.Socket;
	import flash.text.*;

	public class Client extends Sprite
	{
		private var socket:Socket;
		private var myField:TextField;
		public function Client()
		{
			socket = new Socket();
			myField = new TextField();
			// 添加事件处理回调函数
			socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
			socket.connect("localhost", 8888);
			socket.writeUTFBytes("hideto");
			socket.flush();
			myField.x = 20;
			myField.y = 30;
			myField.text = "test";
			myField.autoSize = TextFieldAutoSize.LEFT;
			addChild(myField);
		}
		// 事件处理回调函数
		private function onSocketData(event:ProgressEvent):void {
			while(socket.bytesAvailable) {
				myField.text = socket.readUTFBytes(socket.bytesAvailable);
			}
		}
	}
}


编译运行:
server.erl在Eshell里编译并启动
Eshell > c(server).
Eshell > server:start().
"hideto"  %% 打印接受到的来自AS client的消息

Client.as在Flex Builder 3里编译运行
client.html里显示一个TextField,value为“test”,但是过了一会value变为“Hello, hideto!”,这是因为ActionScript里Socket连接都是 异步的,不能直接从Socket连接中读取数据,而是通过事件处理函数进行读取处理,数据读取完毕后更新TextField的value,所以会看到value由“test”改为“Hello, hideto!”

你可能感兴趣的:(erlang,socket,Flex,Flash,actionscript)