原本打算在window下在quick里面嵌入protobuf,发现错误很多。研究一天都没搞好。只能休息下搞下erlang服务端,先将服务端搞好再回头嵌入protobuf到quick。
在window下不能用rebar,只能自己管理。erlang 是自己弱项。做个简单的服务端基于OTP框架,是一个标准的实现,以后再慢慢扩张吧。
(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 三个文件。
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>>>>>>>>> \n"),
io:format("accept client socket : ~p \n ",[Socket]),
gen_tcp:controlling_process(Socket, self()),
bz_server_sup:start_child();
{error,Reason} ->
io:format("accept error reason : ~p \n",[Reason]),
accept(ListenSocket);
_Res ->
io:format("accept unexpected result : ~p \n",[_Res]),
accept(ListenSocket)
end.
handle_info({tcp,Socket,RawData},State) -> %%数据收取分发
io:format("Socket :~p , RawData : ~p \n",[Socket,RawData]),
%%gen_tcp:send(Socket, "erlang server bin"),
{noreply,RawData};