Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple webserver in Erlang?

Tags:

erlang

Using the default Erlang installation what is the minimum code needed to produce a "Hello world" producing web server?

like image 203
yazz.com Avatar asked Feb 05 '10 11:02

yazz.com


People also ask

What is webserver with example?

Web server hardware is connected to the internet and allows data to be exchanged with other connected devices, while web server software controls how a user accesses hosted files. The web server process is an example of the client/server model. All computers that host websites must have web server software.

Can I build a web server?

It is a common misconception that to build a web server at home, you need to deal with costs and complications. However, the process of building the server is not complicated at all, and you can use old hardware that you have around the house! The only cost you'll have is the electricity bill.

What is web server beginner?

A web server is the computer on which the web pages of your website are stored, who delivers or 'serves' the content of your website to the users through Internet. Simply we can say a computer program that distribute web pages as they are requested requests via HTTP.


2 Answers

Taking "produce" literally, here is a pretty small one. It doesn't even read the request (but does fork on every request, so it's not as minimal possible).

-module(hello).
-export([start/1]).

start(Port) ->
    spawn(fun () -> {ok, Sock} = gen_tcp:listen(Port, [{active, false}]), 
                    loop(Sock) end).

loop(Sock) ->
    {ok, Conn} = gen_tcp:accept(Sock),
    Handler = spawn(fun () -> handle(Conn) end),
    gen_tcp:controlling_process(Conn, Handler),
    loop(Sock).

handle(Conn) ->
    gen_tcp:send(Conn, response("Hello World")),
    gen_tcp:close(Conn).

response(Str) ->
    B = iolist_to_binary(Str),
    iolist_to_binary(
      io_lib:fwrite(
         "HTTP/1.0 200 OK\nContent-Type: text/html\nContent-Length: ~p\n\n~s",
         [size(B), B])).
like image 136
Felix Lange Avatar answered Oct 10 '22 15:10

Felix Lange


For a web server using only the built in libraries check out inets http_server. When in need of some more power but still with simplicity you should check out the mochiweb library. You can google for loads of example code.

like image 23
Jon Gretar Avatar answered Oct 10 '22 16:10

Jon Gretar