本来打算在window下在quick里面嵌入protobuf,发现毛病很多。研究1天都没弄好。只能休息下弄下erlang服务端,先将服务端弄好再回头嵌入protobuf到quick。
在window下不能用rebar,只能自己管理。erlang 是自己弱项。做个简单的服务端基于OTP框架,是1个标准的实现,以后再渐渐扩大吧。
(1).建立好目录doc,ebin,include,priv,src,testClient
(2).在ebin目录下加入元数据server.app,用来启动application
(3).在src下建立bz_server_sup.erl,bz_server_app.erl,bz_server.erl 3个文件。
bz_server_app.erl 用来打包程序,启动,关闭。只提供start/2,stop/1两个函数
start(_StartType,_StartArgs) ->
{ok,LSock} = gen_tcp:listen(?DEFAULT_PORT,?TCP_OPTIONS),
case bz_server_sup:start_link(LSock) of
{ok,Pid} ->
bz_server_sup:start_child(),
{ok,Pid};
Other ->
io:format("bz_server_app Listen error : ~p !",[Other]),
{error,Other}
end.
stop(_State) ->
ok.
bz_server_sup.erl 监听者顶级监听,规定了子监听的启动
start_link(LSock) ->
supervisor:start_link({"127.0.0.1",?SERVER},?MODULE,[LSock]).
start_child() ->
supervisor:start_child(?SERVER,[]).
%%Supervisor callback
init([LSock]) ->
Server = {bz_server, {bz_server, start_link, [LSock]},
temporary, brutal_kill, worker, [bz_server]},
Children = [Server],
RestartStrategy = {simple_one_for_one, 0, 1},
{ok, {RestartStrategy, Children}}.
bz_server.erl. gen_server ,负责等待连接以后的多数实现就在这里实现。以后打算就在这里实现重客户端发送过来的消息在分发下去。
%%-------------private---------------------
accept(ListenSocket) ->
case gen_tcp:accept(ListenSocket) of
{ok,Socket} ->
io:format("<<<<<<<<<<start connect>>>>>>>>>
"),
io:format("accept client socket : ~p
",[Socket]),
gen_tcp:controlling_process(Socket, self()),
bz_server_sup:start_child();
{error,Reason} ->
io:format("accept error reason : ~p
",[Reason]),
accept(ListenSocket);
_Res ->
io:format("accept unexpected result : ~p
",[_Res]),
accept(ListenSocket)
end.
handle_info({tcp,Socket,RawData},State) -> %%数据收取分发
io:format("Socket :~p , RawData : ~p
",[Socket,RawData]),
%%gen_tcp:send(Socket, "erlang server bin"),
{noreply,RawData};
上一篇 再见2014,你好2015!