To paste a simple Web server:
Httpd.erl
% Httpd.erl-microhttpd-module (httpd).
-author ("ninhenry@gmail.com").
-export ([START/0,START/1,START/2,PROCESS/2]).
-import (REGEXP,[SPLIT/2]).
-define (defport,8888).
-define (Docroot, "public").
Start ()-> start (? defport,?docroot).
Start (Port)-> start (port,?docroot). Start (port,docroot)-> case Gen_tcp:listen (Port, [Binary,{packet, 0},{active, false}]) of {OK, lsock}-> Server
_loop (Lsock,docroot);
{error, Reason}-> exit ({Port,reason}) end. Percent% main Server loop-wait for next connection, spawn child to process it Server_loop (lsock,docroot)-> case gen_tcp : Accept (Lsock) of {OK, sock}-> spawn (?
Module,process,[sock,docroot]), Server_loop (Lsock,docroot);
{error, Reason}-> exit ({Accept,reason}) end. % percent Process current connection process (sock,docroot)-> Req = Do_recv (sock), {ok,[cmd|[ name| [Vers|_]]]} = Split (Req, "[\ r \ n]"), FileName = docroot + + name, Logreq = CMD + + "" + + name + + "" + + vers,
Resp = Case File:read_file (FileName) of {OK, data}-> Io:format ("~p ~p ok~n", [Logreq,filename]), data; {error, Reason}-> Io:format ("~p ~p failed ~p~n", [Logreq,filename,reason]), Error_response (Logreq,file:format
_error (Reason)) end, Do_send (SOCK,RESP), Gen_tcp:close (sock). Percent% construct HTML for failure message error_response (Logreq,reason)-> "
The
Runtime builds a public directory locally in Httpd.erl, places a index.html file in the public directory
, and then Httpd:start () starts the server to access http://localhost:8888/ Index.html the