A Web server code instance implemented by Erlang _erlang

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.