这是Erlang中的一个简单服务器。我试图使用spawn / 3生成,但我必须使用spawn / 1才能使它工作。
-module(server_by_name).
-export([start/0]).
start() ->
{ok, Listen} = gen_tcp:listen(1234, [binary, {packet, 0}, {reuseaddr, true}, {active, true}]),
io:format("Server running."),
% --> Why doesn't this work in place of the line below? --> spawn(server_by_name, connect, [Listen]).
spawn(fun() -> connect(Listen) end).
connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> connect(Listen) end),
io:format("Connection accepted on ~p Pid ~p~n", [Socket, self()]),
receive
{tcp, Socket, Bin} ->
Request = parse_request(Bin),
io:format("File requested: ~p~n", [Request]),
LoadHtml = file:read_file(Request),
case LoadHtml of
{ok, Reply} ->
Header = "HTTP/1.1 200 OK \r\n Content-Type:HTML\r\n\r\n",
ConnectCheck = gen_tcp:send(Socket, Header ++ Reply),
io:format("Connection?? ~p~n", [ConnectCheck]);
{error, Reason} ->
io:format("Error in loading html file: ~n~p~n", [Reason]);
end;
{tcp_closed, Socket} ->
io:format("Server socket closed~n")
after 5000 ->
io:format("Client unresponsive~n")
end.
parse_request(Bin) when is_binary(Bin)->
parse_request(binary_to_list(Bin));
parse_request("GET /" ++ RestStr) ->
get_request([], RestStr);
parse_request([_H|T]) ->
parse_request(T).
get_request(Request, [32|_RestStr]) ->
lists:reverse(Request);
get_request(Request, [H|RestStr]) ->
get_request([H|Request], RestStr);
get_request(Request, []) ->
io:format("Unexpected result in server_by_name:get_request()"),
list:reverse(Request).
我已经包含了所有代码,因此您可以复制/粘贴它,并在需要时自行尝试。您只需要一个可以在同一目录中提供的文件,并按名称请求它。显然,它没有安全预防措施等。
答案 0 :(得分:3)
spawn/3
需要导出该功能。您的解决方案非常合理,但您也可以导出connect/1
:
-export([connect/1]). %% do not use, exported for spawn