目录

Erlang - 网络编程( Web Programming)

在Erlang中, inets library可用于在Erlang中构建Web服务器。 让我们看一下Erlang中用于Web编程的一些函数。 可以实现HTTP服务器,也称为httpd来处理HTTP请求。

服务器实现了许多功能,例如 -

  • 安全套接字层(SSL)
  • Erlang脚本接口(ESI)
  • 通用网关接口(CGI)
  • 用户身份验证(使用Mnesia,Dets或纯文本数据库)
  • 通用日志文件格式(支持或不支持disk_log(3))
  • URL别名
  • Action Mappings
  • 目录列表

第一项工作是通过命令启动Web库。

inets:start()

下一步是实现inets库的启动功能,以便可以实现Web服务器。

以下是在Erlang中创建Web服务器进程的示例。

例如 (For example)

-module(helloworld). 
-export([start/0]). 
start() ->
   inets:start(), 
   Pid = inets:start(httpd, [{port, 8081}, {server_name,"httpd_test"}, 
   {server_root,"D://tmp"},{document_root,"D://tmp/htdocs"},
   {bind_address, "localhost"}]), io:fwrite("~p",[Pid]).

关于上述计划,需要注意以下几点。

  • 端口号必须是唯一的,不能被任何其他程序使用。 httpd service将在此端口号上启动。

  • server_rootdocument_root是必需参数。

输出 (Output)

以下是上述程序的输出。

{ok,<0.42.0>}

要在Erlang中实现Hello world web server ,请执行以下步骤 -

Step 1 - 实现以下代码 -

-module(helloworld). 
-export([start/0,service/3]). 
start() ->
   inets:start(httpd, [ 
      {modules, [ 
         mod_alias, 
         mod_auth, 
         mod_esi, 
         mod_actions, 
         mod_cgi, 
         mod_dir,
         mod_get, 
         mod_head, 
         mod_log, 
         mod_disk_log 
      ]}, 
      {port,8081}, 
      {server_name,"helloworld"}, 
      {server_root,"D://tmp"}, 
      {document_root,"D://tmp/htdocs"}, 
      {erl_script_alias, {"/erl", [helloworld]}}, 
      {error_log, "error.log"}, 
      {security_log, "security.log"}, 
      {transfer_log, "transfer.log"}, 
      {mime_types,[ 
         {"html","text/html"}, {"css","text/css"}, {"js","application/x-javascript"} ]} 
   ]). 
service(SessionID, _Env, _Input) -> mod_esi:deliver(SessionID, [ 
   "Content-Type: text/html\r\n\r\n", "<html><body>Hello, World!</body></html>" ]).

Step 2 - 运行代码如下。 编译上面的文件,然后在erl运行以下命令。

c(helloworld).

您将获得以下输出。

{ok,helloworld}

下一个命令是 -

inets:start().

您将获得以下输出。

ok

下一个命令是 -

helloworld:start().

您将获得以下输出。

{ok,<0.50.0>}

Step 3 - 您现在可以访问url - http://localhost:8081/erl/hello_world:service

↑回到顶部↑
WIKI教程 @2018