Fel*_*nge 52
从字面上看"产品",这是一个非常小的.它甚至没有读取请求(但是在每个请求上都进行了分叉,所以它不是那么简单).
-module(hello).
-export([start/1]).
start(Port) ->
spawn(fun () -> {ok, Sock} = gen_tcp:listen(Port, [{active, false}]),
loop(Sock) end).
loop(Sock) ->
{ok, Conn} = gen_tcp:accept(Sock),
Handler = spawn(fun () -> handle(Conn) end),
gen_tcp:controlling_process(Conn, Handler),
loop(Sock).
handle(Conn) ->
gen_tcp:send(Conn, response("Hello World")),
gen_tcp:close(Conn).
response(Str) ->
B = iolist_to_binary(Str),
iolist_to_binary(
io_lib:fwrite(
"HTTP/1.0 200 OK\nContent-Type: text/html\nContent-Length: ~p\n\n~s",
[size(B), B])).
Run Code Online (Sandbox Code Playgroud)
小智 5
类似于gen_tcp上面的示例,但具有更少的代码并且已经提供建议的另一种方法是使用inets库。
%%%
%%% A simple "Hello, world" server in the Erlang.
%%%
-module(hello_erlang).
-export([
main/1,
run_server/0,
start/0
]).
main(_) ->
start(),
receive
stop -> ok
end.
run_server() ->
ok = inets:start(),
{ok, _} = inets:start(httpd, [
{port, 0},
{server_name, "hello_erlang"},
{server_root, "/tmp"},
{document_root, "/tmp"},
{bind_address, "localhost"}
]).
start() -> run_server().
Run Code Online (Sandbox Code Playgroud)
请记住,这将显示您的/tmp目录。
要运行,只需:
$ escript ./hello_erlang.erl
Run Code Online (Sandbox Code Playgroud)