English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Programmation réseau Erlang

En Erlang, la bibliothèque inets peut être utilisée pour construire des serveurs web en Erlang. Voici quelques fonctions utilisées pour le développement web en Erlang. Il est possible d'implémenter un serveur HTTP (également appelé httpd) pour traiter les requêtes HTTP.

Le serveur a implémenté de nombreuses fonctionnalités, telles que-

  • Couche de sécurité de socket (SSL)

  • Interface de script Erlang (ESI)

  • Interface de passerelle réseau générale (CGI)

  • Authentification d'utilisateur (utilisation de Mnesia, Dets ou base de données texte brute)

  • 通用日志文件格式(支持或不支持disk_log(3))

  • URL别名

  • 动作映射

  • 目录列表

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

inets:start()

下一步是实现inets库的start函数,以便实现web服务器。

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

例如

-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 服务。

  • server_rootdocument_root是强制性的参数。

输出

以下是上述程序的输出。

{ok,<0.42.0>}

要在 Erlang 实现 Hello world web 服务器,请执行以下步骤-

Étape 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>" ]).

Étape 2−Exécutez le code suivant. Compilez le fichier ci-dessus, puiserlexécutez les commandes suivantes dans

c(helloworld).

Vous obtiendrez la sortie suivante.

{ok,helloworld}

La prochaine commande est-

inets:start().

Vous obtiendrez la sortie suivante.

ok

La prochaine commande est-

helloworld:start().

Vous obtiendrez la sortie suivante.

{ok,<0.50.0>}

Étape 3−Vous pouvez maintenant accéder à l'url- http://localhost:8081/erl/hello_world:service.