分类: python/ruby
2012-10-07 13:24:33
现有一个erlang套接字编程的例子,监控树如上图。tr_server监听并监创建套接字,打印客户端发送到服务器的数据,并且能创建新tr_server进程继续监听套接字连接;tr_server_sup是个simple_one_for_one的supervisor进程,能够动态地创建tr_server进程。
tr_server
-module(tr_server). -behaviour(gen_server). -export([start_link/1, start_link_v2/1]). -export([init/1, handle_cast/2, handle_info/2, terminate/2]). -record(state, {lsock,socket}). start_link(lsock) -> gen_server:start_link(?module, [lsock], []). init([lsock]) -> send(self(), listen), {ok, #state{lsock=lsock}}. handle_cast(listen, #state{lsock=lsock}) -> %%{ok, lsock} = gen_tcp:listen(port, [{active, once}]), {ok, socket} = gen_tcp:accept(lsock), tr_server_sup:start_child(lsock), {noreply, #state{socket=socket}}. handle_info({tcp, _port, packet}, #state{socket=socket}) -> io:format("~p~n", [packet]), inet:setopts(socket, [{active, once}]), {noreply, #state{socket=socket}}. terminate(_reason, _state) -> ok. send(pid, msg) -> gen_server:cast(pid, msg). |
tr_server的初始化非常简单,仅仅是给自身发送个listen异步消息,这是因为进程的启动是个原子操作,为了避免tr_server的进程创建时间过长,因此把等待客户端连接的动作放到进程启动之后再处理;
客户端与服务端通过套接字的数据会以erlang消息的形式发送给套接字处理进程,其标签为{tcp, port, rawdata},因此必须在handle_info中接收和处理通过套接字接收到的数据;
在erlang中,套接字active模式主要有三种,这里使用的是once,三种模式的简介如下:
active | 说明 |
true | 当套接字接收到数据时,就直接发送给处理进程 |
false | 当套接字接收到数据时,不主动把数据发送给处理进程,需要处理进程从套接字中取 |
once | 当套接字接收到数据时,如果是第一次,就把数据发送给处理进程,否则,不发送(处理程序处理完一次时,可以调用inet:setopts再次把active设置为once) |
tr_server_sup
-module(tr_server_sup). -behaviour(supervisor). -export([start_link/0, start_child/1]). -export([init/1]). -define(child(id, mod, type, args), {id, {mod, start_link, args}, temporary, brutal_kill, type, [mod]}). start_link() -> supervisor:start_link({local, ?module}, ?module, []). start_child(lsock)-> supervisor:start_child(?module, [lsock]). init([]) -> {ok, {{simple_one_for_one, 0, 1}, [?child(tr_server, tr_server, worker, [])]}}. |
tr_server_sup是个simple_one_for_one进程,其启动时不启动进程,需要调用tr_server_sup:start_child(lsock)动态地创建tr_server worker进程;
启动tr_server_sup
启动tr_server_sup时需要启动第一个tr_server进程,之后tr_server会调用tr_server_sup动态地创建tr_server进程。
2012-12-01 10:36:00
ptc creo elements/pro 5.0 m070 working for win32-iso 1dvd(最新多语言正式版包括简、繁体中文)
ptc creo elements/pro 5.0 m070 working for win64-iso 1dvd
ptc creo elements view (ex product view) v10 f000 build 93 pro multilanguage win32 1cd
ptc creo elements view (ex product view) v10 f000 build 93 pro multilanguage win64 1cd
ptc pro/e wildfire pro/mechancia 4.0 m110 working for win32-iso 1dvd(最新多语言正式版包括简、繁体中文)
ptc pro/e wil