的代碼如下:模擬線程池由二郎實現的web服務器不工作
-module(rudy).
-export([init/1,handler/1,request/1,reply/1, start/1, stop/0]).
start(Port) ->
register(rudy, spawn(fun() ->
init(Port) end)).
stop() ->
exit(whereis(rudy), "time to die").
init(Port) ->
Opt = [list, {active, false}, {reuseaddr, true}],
case gen_tcp:listen(Port, Opt) of % opens a listening socket
{ok, Listen} ->
spawn_many(3,Listen),
%% handler(Listen),
ok;
{error, _Error} -> error
end.
handler(Listen) ->
case gen_tcp:accept(Listen) of % listen to the socket
{ok, Client} ->
request(Client),
gen_tcp:close(Client),
handler(Listen);
{error, _Error} -> error
end.
%% gen_tcp:close(Listen). % close the socket
request(Client) ->
Recv = gen_tcp:recv(Client, 0),
case Recv of
{ok, Str} ->
Request = http:parse_request(Str),
Response = reply(Request),
gen_tcp:send(Client, Response);
{error, Error} ->
io:format("rudy: error: ~w~n", [Error])
end,
gen_tcp:close(Client).
reply({{get, URI, _}, _, _}) ->
timer:sleep(40),
http:ok(URI).
spawn_many(0, _Listen)-> ok;
spawn_many(N, Listen)->
spawn(rudy,handler,[Listen]),
spawn_many(N - 1, Listen).
我打算創建3監聽套接字的客戶端連接到,但是這個代碼沒有按」 t執行rudy:start(8027).
,然後從網絡瀏覽器訪問http://localhost:8027/。
罪魁禍首究竟在哪裏?非常感謝。
再次感謝您,我是Erlang的新手,您的詳細解答非常有幫助:] – Judking