如何在Erlang中编写一个简单的Web服务器? [英] How to write a simple webserver in Erlang?
本文介绍了如何在Erlang中编写一个简单的Web服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
使用默认的Erlang安装,生成Hello world以生产字面意思,这里是一个很小的。它甚至没有读取请求(但是在每个请求上都是fork,所以它不是那么小)。
-module (你好)。
-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)。
句柄(Conn) - >
gen_tcp:send(Conn,response(Hello World)),
gen_tcp:close(Conn)。
响应(Str) - >
B = iolist_to_binary(Str),
iolist_to_binary(
io_lib:fwrite(
HTTP / 1.0 200 OK\\\
Content-Type:text / html\\\
Content-Length: 〜p\\\
\\\
〜s,
[size(B),B]))。
Using the default Erlang installation what is the minimum code needed to produce a "Hello world" producing web server?
解决方案
Taking "produce" literally, here is a pretty small one. It doesn't even read the request (but does fork on every request, so it's not as minimal possible).
-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])).
这篇关于如何在Erlang中编写一个简单的Web服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文