Erlang和ActionScript3的Socket通讯

server.erl
[code]
-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.
[/code]

Client.as
[code]
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);
}
}
}
}
[/code]

编译运行:
server.erl在Eshell里编译并启动
[code]
Eshell > c(server).
Eshell > server:start().
"hideto" %% 打印接受到的来自AS client的消息
[/code]
Client.as在Flex Builder 3里编译运行
client.html里显示一个TextField,value为“test”,但是过了一会value变为“Hello, hideto!”,这是因为ActionScript里Socket连接都是[color=red][b]异步[/b][/color]的,不能直接从Socket连接中读取数据,而是通过事件处理函数进行读取处理,数据读取完毕后更新TextField的value,所以会看到value由“test”改为“Hello, hideto!”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值