当前位置: 代码网 > it编程>前端脚本>Erlang > Erlang实现的一个Web服务器代码实例

Erlang实现的一个Web服务器代码实例

2024年05月15日 Erlang 我要评论
转贴一个简单的web服务器:httpd.erl %% httpd.erl - microhttpd -module(httpd). -author("ninhenry@gmail.com"). -e

转贴一个简单的web服务器:

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. 
 
%% 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. 
 
%% 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). 
 
%% construct html for failure message 
error_response(logreq,reason) -> 
 "<html><head><title>request failed</title></head><body>\n" ++ 
 "<h1>request failed</h1>\n" ++ "your request to " ++ logreq ++ 
 " failed due to: " ++ reason ++ "\n</body></html>\n". 
 
%% send a line of text to the socket 
do_send(sock,msg) -> 
 case gen_tcp:send(sock, msg) of 
  ok -> ok; 
   {error, reason} -> exit(reason) 
 end. 
 
%% receive data from the socket 
do_recv(sock) -> 
 case gen_tcp:recv(sock, 0) of 
  {ok, bin} -> binary_to_list(bin); 
   {error, closed} -> exit(closed); 
   {error, reason} -> exit(reason) 
 end

运行时在httpd.erl本地建一个public目录,public目录里放一个index.html文件
然后httpd:start()启动服务器,就可以访问http://localhost:8888/index.html

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com