hello world_web server - rosetta code

Upload: sergeviardot

Post on 08-Aug-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    1/18

    Helloworld/Web

    serverYou areencouraged to

    solve this task accordingto the task description,using any language youmay know.

    Hello world/Web server

    From Rosetta Code< Hello world

    The browser is the new GUI!

    The task is to serve our standard text "Goodbye, World!" to

    http://localhost:8080/ so that it can be viewed with a web browser.The provided solution must start or implement a server that acceptsmultiple client connections and serves text as requested.

    Note that starting a web browser or opening a new window withthis URL is not part of the task. Additionally, it is permissible toserve the provided page as a plain text file (there is no requirementto serve properly formatted HTML here). The browser will generally

    do the right thing with simple text like this.

    Contents

    1 Ada2 AWK3 BBC BASIC4 C5 C++6 C#7 D8 Delphi9 Dylan.NET10 Erlang11 Fantom12 Go13 Haskell14 Io15 J

    16 Java17 JavaScript18 Liberty BASIC19 Modula-220 NetRexx21 Objeck22 OCaml23 Opa24 Perl25 Perl 626 PicoLisp

    27 Prolog28 PureBasic29 PHP30 Python

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    2/18

    31 Racket32 REALbasic33 Ruby34 Run BASIC35 Salmon36 Seed737 Smalltalk

    38 Tcl

    Ada

    Library: AWS

    Uses many defaults, such as 5 max simultaneous connections.

    with AWS; use AWS;

    with AWS.Response;

    with AWS.Server;

    with AWS.Status;

    with Ada.Text_IO; use Ada.Text_IO;

    procedure HelloHTTP is

    function CB (Request : Status.Data)return Response.Datais

    pragma Unreferenced (Request);

    begin

    return Response.Build("text/html", "Hello world!");

    end CB;

    TheServer : Server.HTTP;

    ch : Character;

    begin

    Server.Start(TheServer, "Rosettacode",

    Callback => CB'Unrestricted_Access, Port => 8080);Put_Line ("Press any key to quit."); Get_Immediate (ch);

    Server.Shutdown(TheServer);

    end HelloHTTP;

    AWK

    With GNU AWK (gawk) a simple web server can be implemented. The example is taken fromhere [1] (http://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html#Primitive-Service)(Documentation is licensed under GNU Free Documentation License, Version 1.3)

    #!/usr/bin/gawk -f

    BEGIN{

    RS = ORS = "\r\n"

    HttpService = "/inet/tcp/8080/0/0"

    Hello = "" \

    "A Famous Greeting" \

    "Hello, world"

    Len = length(Hello) + length(ORS)

    print"HTTP/1.0 200 OK" |& HttpService

    print"Content-Length: " Len ORS |& HttpService

    print Hello |& HttpService

    while((HttpService |& getline) > 0)

    continue;

    close(HttpService)

    }

    BBC BASIC

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    3/18

    Works with: BBC BASIC for Windows

    This explicitly supports multiple concurrent connections.

    INSTALL @lib$+"SOCKLIB"

    PROC_initsockets

    maxSess% = 8

    DIM sock%(maxSess%-1), rcvd$(maxSess%-1), Buffer% 255

    ON ERROR PRINT REPORT$ : PROC_exitsockets : END

    ON CLOSE PROC_exitsockets : QUIT

    port$ = "8080"

    host$ = FN_gethostname

    PRINT "Host name is " host$

    listen% = FN_tcplisten(host$, port$)

    PRINT "Listening on port ";port$

    REPEAT

    socket% = FN_check_connection(listen%)

    IF socket% THEN

    FOR i% = 0 TO maxSess%-1

    IF sock%(i%) = 0 THEN

    sock%(i%) = socket%

    rcvd$(i%) = ""

    PRINT "Connection on socket "; sock%(i%) " opened"

    EXIT FOR

    ENDIF

    NEXT i%

    listen% = FN_tcplisten(host$, port$)

    ENDIF

    FOR i% = 0 TO maxSess%-1

    IF sock%(i%) THEN

    res% = FN_readsocket(sock%(i%), Buffer%, 256)

    IF res% >= 0 THEN

    Buffer%?res% = 0

    rcvd$(i%) += $$Buffer%

    IF LEFT$(rcvd$(i%),4) = "GET " AND ( \

    \ RIGHT$(rcvd$(i%),4) = CHR$13+CHR$10+CHR$13+CHR$10 OR \

    \ RIGHT$(rcvd$(i%),4) = CHR$10+CHR$13+CHR$10+CHR$13 OR \\ RIGHT$(rcvd$(i%),2) = CHR$10+CHR$10 ) THEN

    rcvd$(i%) = ""

    IF FN_writelinesocket(sock%(i%), "HTTP/1.0 200 OK")

    IF FN_writelinesocket(sock%(i%), "Content-type: text/html")

    IF FN_writelinesocket(sock%(i%), "")

    IF FN_writelinesocket(sock%(i%), "Hello World!")

    IF FN_writelinesocket(sock%(i%), "Hello World!")

    IF FN_writelinesocket(sock%(i%), "")

    PROC_closesocket(sock%(i%))

    PRINT "Connection on socket " ; sock%(i%) " closed (local)"

    sock%(i%) = 0

    ENDIF

    ELSE

    PROC_closesocket(sock%(i%))

    PRINT "Connection on socket " ; sock%(i%) " closed (remote)"

    sock%(i%) = 0

    ENDIF

    ENDIF

    NEXT i%

    WAIT 0

    UNTIL FALSE

    END

    C

    This is, um, slightly longer than what other languages would be.

    #include

    #include

    #include

    #include

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    4/18

    #include

    #include

    #include

    #include

    #include

    char response[] = "HTTP/1.1 200 OK\r\n"

    "Content-Type: text/html; charset=UTF-8\r\n\r\n"

    "Bye-bye baby bye-bye"

    "body { background-color: #111 }"

    "h1 { font-size:4cm; text-align: center; color: black;"

    " text-shadow: 0 0 2mm red}"

    "Goodbye, world!\r\n";

    int main()

    {

    int one = 1, client_fd;

    struct sockaddr_in svr_addr, cli_addr;

    socklen_t sin_len = sizeof(cli_addr);

    int sock = socket(AF_INET, SOCK_STREAM, 0);

    if(sock < 0)

    err(1, "can't open socket");

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

    int port = 8080;

    svr_addr.sin_family = AF_INET;

    svr_addr.sin_addr.s_addr = INADDR_ANY;

    svr_addr.sin_port = htons(port);

    if(bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1){

    close(sock);

    err(1, "Can't bind");

    }

    listen(sock, 5);

    while(1){

    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);

    printf("got connection\n");

    if(client_fd == -1){

    perror("Can't accept");

    continue;}

    write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/

    close(client_fd);

    }

    }

    C++

    C version compiles as C++ (known for G++ on Linux)

    C#

    using System.Text;

    using System.Net.Sockets;

    using System.Net;

    namespace WebServer

    {

    class GoodByeWorld

    {

    staticvoid Main(string[] args)

    {

    conststring msg = "\n\nGoodbye, world!\n\n\n";

    constint port = 8080;

    bool serverRunning = true;

    TcpListener tcpListener = new TcpListener(IPAddress.Any, port);

    tcpListener.Start();

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    5/18

    while(serverRunning)

    {

    Socket socketConnection = tcpListener.AcceptSocket();

    byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);

    socketConnection.Send(bMsg);

    socketConnection.Disconnect(true);

    }

    }

    }

    }

    D

    Using sockets only, also shows use of heredoc syntax, std.array.replace, and casting to bool tosatisfy the while conditional.

    import std.socket, std.array;

    ushort port = 8080;

    void main(){

    Socket listener = new TcpSocket;

    listener.bind(new InternetAddress(port));

    listener.listen(10);

    Socket currSock;

    while(cast(bool)(currSock = listener.accept())){

    currSock.sendTo(replace(q"EOF

    HTTP/1.1 200 OK

    Content-Type: text/html; charset=UTF-8

    Hello, world!

    Hello, world!

    EOF", "\n", "\r\n"));

    currSock.close();

    }

    }

    Delphi

    program HelloWorldWebServer;

    {$APPTYPE CONSOLE}

    uses SysUtils, IdContext, IdCustomHTTPServer, IdHTTPServer;

    type

    TWebServer = class

    private

    FHTTPServer: TIdHTTPServer;

    public

    constructor Create;

    destructor Destroy; override;

    procedure HTTPServerCommandGet(AContext: TIdContext;

    ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);

    end;

    constructor TWebServer.Create;

    begin

    FHTTPServer := TIdHTTPServer.Create(nil);FHTTPServer.DefaultPort := 8080;

    FHTTPServer.OnCommandGet := HTTPServerCommandGet;

    FHTTPServer.Active := True;

    end;

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    6/18

    destructor TWebServer.Destroy;

    begin

    FHTTPServer.Active := False;

    FHTTPServer.Free;

    inherited Destroy;

    end;

    procedure TWebServer.HTTPServerCommandGet(AContext: TIdContext;

    ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);

    begin

    AResponseInfo.ContentText := 'Goodbye, World!';

    end;

    var

    lWebServer: TWebServer;

    begin

    lWebServer := TWebServer.Create;

    try

    Writeln('Delphi Hello world/Web server ');

    Writeln('Press Enter to quit');

    Readln;

    finally

    lWebServer.Free;

    end;

    end.

    Dylan.NET

    //compile with dylan.NET 11.2.9.6 or later!!

    #refstdasm "mscorlib.dll"

    #refstdasm "System.dll"

    import System.Text

    import System.Net.Sockets

    import System.Net

    assembly helloweb exe

    ver 1.1.0.0

    namespace WebServer

    class public auto ansi GoodByeWorld

    method public static void main(var args as string[])

    var msg as string = c"\n\nGoodbye, world!\n\n\n"

    var port as integer = 8080

    var serverRunning as boolean = true

    var tcpListener as TcpListener = new TcpListener(IPAddress::Any, port)

    tcpListener::Start()

    do while serverRunning

    var socketConnection as Socket = tcpListener::AcceptSocket()

    var bMsg as byte[] = Encoding::get_ASCII()::GetBytes(msg::ToCharArray(), 0, msg::get_Len

    socketConnection::Send(bMsg)

    socketConnection::Disconnect(true)

    end do

    end method

    end class

    end namespace

    Erlang

    Using builtin HTTP server with call back to do/1. It only lasts 30 seconds (30000 milliseconds),then it is stopped. I fail to see how a longer time will serve any purpose.

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    7/18

    -module( hello_world_web_server ).

    -export([do/1, httpd_start/2, httpd_stop/1, task/0]).

    do( _Data ) ->

    {proceed, [{response,{200,"Goodbye, World!"}}]}.

    httpd_start( Port, Module ) ->

    Arguments = [{bind_address, "localhost"}, {port, Port}, {ipfamily, inet},

    {modules, [Module]},

    {server_name,erlang:atom_to_list(Module)}, {server_root,"."}, {document_root,"."}],

    {ok, Pid} = inets:start( httpd, Arguments, stand_alone ),

    Pid.

    httpd_stop( Pid ) ->

    inets:stop( stand_alone, Pid ).

    task() ->

    Pid = httpd_start(8080, ?MODULE ),

    timer:sleep(30000),

    httpd_stop( Pid ).

    Fantom

    using web

    using wisp

    const class HelloMod : WebMod // provides the content

    {

    override Void onGet ()

    {

    res.headers["Content-Type"] = "text/plain; charset=utf-8"

    res.out.print ("Goodbye, World!")

    }

    }

    class HelloWeb

    {

    Void main (){

    WispService // creates the web service

    {

    port = 8080

    root = HelloMod()

    }.start

    while (true) {} // stay running

    }

    }

    Go

    package main

    import (

    "fmt"

    "log"

    "net/http"

    )

    func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {

    fmt.Fprintln(w, "Goodbye, World!")

    })

    log.Fatal(http.ListenAndServe(":8080", nil))

    }

    Haskell

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    ur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    8/18

    Lightweightly concurrent "hello world" web server using the conduit (http://www.yesodweb.com/book/conduits) stack:

    {-# LANGUAGE OverloadedStrings #-}

    import Data.ByteString.Char8 ()

    import Data.Conduit (($$), yield )

    import Data.Conduit.Network ( ServerSettings(..), runTCPServer )

    main :: IO()main = runTCPServer (ServerSettings 8080"127.0.0.1") $ const(yield response $$)

    where response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"

    Or using only "standard" features (base (http://hackage.haskell.org/package/base) , bytestring(http://hackage.haskell.org/package/bytestring) and network (http://hackage.haskell.org/package/network) from the Haskell Platform (http://hackage.haskell.org/platform/) ):

    {-# LANGUAGE OverloadedStrings #-}

    import Data.ByteString.Char8 ()

    import Network hiding( accept )

    import Network.Socket ( accept )import Network.Socket.ByteString ( sendAll )

    import Control.Monad( forever )

    import Control.Exception ( bracket, finally )

    import Control.Concurrent ( forkIO )

    main :: IO()

    main = bracket (listenOn $ PortNumber 8080) sClose loop where

    loop s = forever $ forkIO . request . fst =

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    9/18

    WebServer := Serverclonedo(

    setPort(8080)

    handleSocket := method(aSocket,

    WebRequest clone asyncSend(handleSocket(aSocket))

    )

    )

    WebServer start

    J

    If the desire is to use the browser as a gui, the easiest thing to do would be to download(http://www.jsoftware.com/stable.htm) j7 (http://www.jsoftware.com/docs/help701

    /user/relhigh.htm) , edit the jhs script to start on port 8080, start jhs, visit http://127.0.0.1:8080/jijxthen enter the text:

    'Goodbye, World!'

    This will compute the desired result and display it (actually, it will be displayed twice since theoriginal string will also be displayed). This would be even simpler if you could just use the defaultjhs port (65001)... Alternatively, a jhs form could be used (but this would not have the exact urlstructure specified).

    However, if the desire is to implement the task exactly, any of approaches at j:JWebServer mightbe used.

    For example, here is a web server which ignores the client's request and always returnsGoodbye, World:

    hello=: verb define

    8080 hello yNB. try to use port 8080 by default

    :

    port=: x

    require 'socket'

    coinsert 'jsocket'

    sdclose ; sdcheck sdgetsockets ''

    server=: {. ; sdcheck sdsocket ''

    sdcheck sdbind server; AF_INET; ''; port

    sdcheck sdlisten server, 1

    while.1do.

    while.

    server e. ready=: >{. sdcheck sdselect (sdcheck sdgetsockets ''),'';'';

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    10/18

    server waits for one tcp packet before responding.) If parsing of the request is desired, one of themore complicated implementations at j:JWebServer should be used instead (but that's not reallyrelevant for this task, except perhaps to require complete headers before responding, with brokenbrowsers which send multiple tcp packets for the request).

    Java

    Multiple requests will be served in the order that they reach the server, with a queue size limit of50 waiting requests imposed by default in the ServerSocket class (may be changed by adding a

    second positive integer argument to the ServerSocket constructor).

    importjava.io.IOException;

    importjava.io.PrintWriter;

    importjava.net.ServerSocket;

    importjava.net.Socket;

    publicclass HelloWorld{

    publicstaticvoid main(String[] args)throwsIOException{

    ServerSocket listener = newServerSocket(8080);

    while(true){

    Socket sock = listener.accept();

    newPrintWriter(sock.getOutputStream(), true).

    println("Goodbye, World!");

    sock.close();

    }

    }

    }

    JavaScript

    Works with: Node.js

    var http = require('http');

    http.createServer(function(req, res){

    res.writeHead(200, {'Content-Type': 'text/plain'});

    res.end('Goodbye, World!\n');

    }).listen(8080, '127.0.0.1');

    It scales:

    $ curl http://localhost:8080/

    Goodbye, World!

    # httperf --port=8080 --num-conns=10000Request rate: 1813.1 req/s (0.6 ms/req)

    # httperf --port=8080 --num-conns=10000 --num-calls=10

    Request rate: 4869.1 req/s (0.2 ms/req)

    # httperf --port=8080 --num-conns=10000 --num-calls=100

    Request rate: 5689.0 req/s (0.2 ms/req)

    with no errors.

    Liberty BASIC

    This is difficult, although possible, in Liberty BASIC, but it's close relative Run BASIC is designedfor serving webpages easily. The task becomes simply ..

    print"hello world!"

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    11/18

    Modula-2

    This is a CGI executable:

    MODULE access;

    FROM InOut IMPORT WriteString, WriteLn;

    BEGIN

    WriteString ("Content-Type : text/plain");

    WriteLn;

    WriteLn;

    WriteString ("Hello web wide world.");

    WriteLn

    END access.

    NetRexx

    Translation of: Java

    /* NetRexx */

    options replace format comments java crossref symbols binary

    class RHelloWorldWebServer public

    propertiespublicconstant

    isTrue = boolean (1 == 1)

    isFalse = boolean (1 \== 1)

    greeting1 = "Goodbye, World!"

    greeting2 = '' -

    || 'HTTP/1.1 200 OK\r\n' -

    || 'Content-Type: text/html; charset=UTF-8\r\n\r\n' -

    || '\r\n' -

    || '

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    12/18

    function : Main(args : String[]) ~ Nil{

    server := TCPSocketServer->New(8080);

    if(server->Listen(5)){

    while(true){

    client := server->Accept();

    client->WriteString("\n\nGoodbye, world!\n\n\n");

    client->Close();

    };

    };

    server->Close();

    }

    }}

    OCaml

    This code is derived from this ocaml-unix documentation (http://ocamlunix.forge.ocamlcore.org/sockets.html#htoc54) .

    let try_finalise f x finally y =

    let res = try f x with e -> finally y; raise e infinally y;

    res

    letrec restart_on_EINTR f x =

    try f x withUnix.Unix_error (Unix.EINTR, _, _) -> restart_on_EINTR f x

    let double_fork_treatment server service (client_descr, _as client) =

    let treat () =

    matchUnix.fork ()with

    | 0 ->

    ifUnix.fork () 0thenexit0;

    Unix.close server; service client; exit0

    | k ->

    ignore(restart_on_EINTR (Unix.waitpid []) k)

    in

    try_finalise treat ()Unix.close client_descr

    let install_tcp_server_socket addr =

    let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0in

    try

    Unix.bind s addr;

    Unix.listen s 10;

    s

    with e -> Unix.close s; raise e

    let tcp_server treat_connection addr =

    ignore(Sys.signal Sys.sigpipe Sys.Signal_ignore);

    let server_sock = install_tcp_server_socket addr in

    whiletruedo

    let client = restart_on_EINTR Unix.accept server_sock in

    treat_connection server_sock client

    done

    let server () =

    let port = 8080in

    let host = (Unix.gethostbyname (Unix.gethostname())).Unix.h_addr_list.(0)in

    let addr = Unix.ADDR_INET (host, port)in

    let treat sock (client_sock, client_addr as client) =

    let service (s, _) =

    let response = "\

    HTTP/1.1 200 OK\r\n\

    Content-Type: text/html; charset=UTF-8\r\n\r\n\

    Goodbye, world!\

    body { background-color: #0FF }\

    h1 { font-size:3em; color: black; }\

    Goodbye, world!\r\n"

    in

    Unix.write s response 0(String.length response); in

    double_fork_treatment sock service client

    in

    tcp_server treat addr

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    13/18

    let _ =

    Unix.handle_unix_error server ()

    Opa

    From Opa documentation (http://doc.opalang.org/index.html#_a_first_peek_at_opa) :

    server = one_page_server("Hello", -> Goodbye, world)

    Compile and run:

    opa file.opa --

    Perl

    use Socket;

    my $port = 8080;

    my $protocol = getprotobyname("tcp");

    socket( SOCK, PF_INET, SOCK_STREAM, $protocol )ordie"couldn't open a socket: $!";

    # PF_INET to indicate that this socket will connect to the internet domain

    # SOCK_STREAM indicates a TCP stream, SOCK_DGRAM would indicate UDP communication

    setsockopt( SOCK, SOL_SOCKET, SO_REUSEADDR, 1)ordie"couldn't set socket options: $!";

    # SOL_SOCKET to indicate that we are setting an option on the socket instead of the protocol

    # mark the socket reusable

    bind( SOCK, sockaddr_in($port, INADDR_ANY))ordie"couldn't bind socket to port $port: $!";

    # bind our socket to $port, allowing any IP to connect

    listen( SOCK, SOMAXCONN )ordie"couldn't listen to port $port: $!";

    # start listening for incoming connections

    while(accept(CLIENT, SOCK)){

    print CLIENT "HTTP/1.1 200 OK\r\n" .

    "Content-Type: text/html; charset=UTF-8\r\n\r\n" .

    "Goodbye, world!Goodbye, world!\r\n

    close CLIENT;

    }

    Various modules exist for using sockets, including the popular IO::Socket which provides asimpler and more friendly OO interface for the socket layer. Here is the solution using thismodule:

    Library: IO::Socket::INETINET

    use IO::Socket::INET;

    my $sock = new IO::Socket::INET( LocalAddr => "127.0.0.1:8080",

    Listen => 1,

    Reuse => 1, )ordie"Could not create socket: $!";

    while(my $client = $sock->accept()){

    print $client "HTTP/1.1 200 OK\r\n" .

    "Content-Type: text/html; charset=UTF-8\r\n\r\n" .

    "Goodbye, world!Goodbye, world!\r\

    close $client;

    }

    Using Perl's glue power, provide a suicide note with visitor counter via netcat:

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    14/18

    while(++(our $vn)){

    open NC, "|-", qw(nc -l -p 8080 -q1);

    print NC "HTTP/1.0 200 OK\xd\xa",

    "Content-type: text/plain; charset=utf-8\xd\xa\xd\xa",

    "Goodbye, World! (hello, visitor No. $vn!)\xd\xa";

    }

    Here's another solution using Plack (may be found on CPAN):

    use Plack::Runner;

    my $app = sub{

    return[200,

    ['Content-Type' => 'text/html; charset=UTF-8'],

    ['Goodbye, world!Goodbye, world!']

    ]

    };

    my $runner = Plack::Runner->new;

    $runner->parse_options('--host' => 'localhost', '--port' => 8080);

    $runner->run($app);

    When using plackup, then this may be compressed to one line:

    my $app = sub{return[200, ['Content-Type' => 'text/html; charset=UTF-8'], ['Go

    Use

    plackup --host localhost --port 8080 script.psgi

    to start the webserver.

    Perl 6

    Works with: Rakudo

    my $sock = IO::Socket::INET.new(:localhost('0.0.0.0'), :localport(8080), :listen);

    say"Goodbye Web Server listening on $sock.localhost():$sock.localport()";

    while $sock.accept -> $client {

    $client.send: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n

    $client.close;

    }

    PicoLisp

    Contents of the file "goodbye.l":

    (html 0 "Bye" NIL NIL

    "Goodbye, World!" )

    Start server:

    $ pil @lib/http.l @lib/xhtml.l -'server 8080 "goodbye.l"' -wait

    Prolog

    Works with: SWI Prolog

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    15/18

    Works with: YAP

    % The following modules are used in the main module to start a server.

    :- use_module(library(http/thread_httpd)).

    :- use_module(library(http/http_dispatch)).

    % The following module is used in every module that describes a page.

    :- use_module(library(http/html_write)).

    % Main entry point: starts the server on port 8080.

    server :- http_server(http_dispatch, [port(8080)]).

    % Defines the handler for the root URI /.

    :- http_handler('/', say_goodbye, []).

    % Defines the actual page content.

    % In this case we're returning a page with the title "Howdy" and the content,

    % wrapped in tags, "Goodbye, World!".

    say_goodbye(_Request) :- reply_html_page([title('Howdy')],

    [h1('Goodbye, World!')]).

    PureBasic

    IfInitNetwork() = 0

    MessageRequester("Error", "Can't initialize the network !")

    End

    EndIf

    Port = 8080

    IfCreateNetworkServer(0, Port)

    Repeat

    Delay(1)

    SEvent = NetworkServerEvent()

    If SEvent

    ClientID = EventClient()

    Select SEvent

    Case #PB_NetworkEvent_DataSendNetworkData(ClientID,@"Goodbye, World!",Len("Goodbye, World!

    CloseNetworkConnection(ClientID)

    EndSelect

    EndIf

    ForEver

    Else

    MessageRequester("Error", "Can't create the server (port in use ?).")

    EndIf

    PHP

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    16/18

    Python

    def app(environ, start_response):

    start_response('200 OK', [])

    yield"Goodbye, World!"

    if __name__ == '__main__':

    from wsgiref.simple_serverimport make_server

    server = make_server('127.0.0.1', 8080, app)

    server.serve_forever()

    Racket

    #lang racket

    (require web-server/servlet web-server/servlet-env)

    (define (start req) (response/xexpr "Goodbye, World!"))

    (serve/servlet start #:port 8080 #:servlet-path "/")

    REALbasic

    Class HTTPSock

    Inherits TCPSocket

    Event Sub DataAvailable()

    Dim headers AsNew InternetHeaders

    headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))

    headers.AppendHeader("Content-Type", "text/plain")

    headers.AppendHeader("Content-Encoding", "identity")

    headers.AppendHeader("Connection", "close")

    Dim data AsString = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + En

    Me.Write(data)Me.Close

    EndSub

    End Class

    Class HTTPServ

    Inherits ServerSocket

    Event Sub AddSocket() As TCPSocket

    Return New HTTPSock

    EndSub

    End Class

    Class App

    Inherits Application

    Event Sub Run(Args() AsString)

    Dim sock AsNew HTTPServ

    sock.Port = 8080sock.Listen()

    WhileTrue

    App.DoEvents

    Wend

    EndSub

    End Class

    Ruby

    Using the WEBrick module from Ruby's standard library.

    require'webrick'

    server = WEBrick::HTTPServer.new(:Port => 8080)

    server.mount_proc('/'){|request, response| response.body = "Goodbye, World!"}

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    17/18

    trap("INT"){server.shutdown}

    server.start

    Using the sinatra (http://www.sinatrarb.com/) gem:

    require'sinatra'

    get("/"){"Goodbye, World!"}

    Run BASIC

    html "Hello World!"

    Salmon

    use "http.salm" : "http.si";

    /* Don't do any logging. */

    procedure log(...) { };

    simple_http_server(8080, procedure(header, connection)

    { respond_text(connection, "Goodbye, World!"); });

    Seed7

    The code below was inspired by the example code for the function openInetListener(http://seed7.sourceforge.net/libraries/listener.htm#openInetListener%28in_integer%29) .

    $ include "seed7_05.s7i";

    include "listener.s7i";

    const proc: main is func

    local

    var listener: aListener is listener.value;

    var file: sock is STD_NULL;

    begin

    aListener := openInetListener(8080);

    listen(aListener, 10);

    while TRUE do

    sock := accept(aListener);

    write(sock, "HTTP/1.1 200 OK\r\n\

    \Content-Type: text/html; charset=UTF-8\r\n\

    \\r\n\

    \Hello, world!\n");close(sock);

    end while;

    end func;

    Smalltalk

    Works with: Smalltalk/X

    starting server:

    Smalltalk loadPackage:'stx:goodies/webServer'. "usually already loaded"

    |myServer service|

    myServer := HTTPServer startServerOnPort:8082.

    service := HTTPPluggableActionService new.

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server

    sur 18 19/07/2013 19:57

  • 8/22/2019 Hello World_Web Server - Rosetta Code

    18/18

    service

    register:[:request |

    self halt: 'debugging'.

    request reply:'Hello World'

    ]

    as:'hello'.

    service linkNames:#('/').

    service registerServiceOn: myServer.

    myServer start.

    Be aware that the above is an ad-hoc minimal scripting example. Normally, a service subclass isused and response handlers are defined as methods of it (not as action blocks). Also, servicesand HTML generation is usually done using a framework (at least DOM-based, but usually a

    higher level toolkit). Especially take a look at smalltalk frameworks like Aida, Seaside, VisualWaveetc.

    Tcl

    This version is adapted from the Tcler's Wiki (http://wiki.tcl.tk/28412) .

    proc accept {chan addr port}{

    while{[gets $chan] ne ""}{}

    puts $chan "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n"

    puts $chan "Goodbye, World!"

    close $chan

    }

    socket -server accept 8080

    vwait forever

    Retrieved from "http://rosettacode.org/mw/index.php?title=Hello_world/Web_server&oldid=160111"

    Categories: Programming Tasks Networking and Web Interaction Ada AWS AWK

    BBC BASIC C C++ C sharp D Delphi Dylan.NET Erlang Fantom Go Haskell Io JJava JavaScript Liberty BASIC Modula-2 NetRexx Objeck OCaml Opa Perl Perl 6

    PicoLisp Prolog PureBasic PHP Python Racket REALbasic Ruby Run BASIC

    Salmon Seed7 Smalltalk Tcl GUISS/Omit Locomotive Basic/Omit

    Lotus 123 Macro Scripting/Omit ML/I/Omit ZX Spectrum Basic/Omit Retro/Omit

    Maxima/Omit

    This page was last modified on 4 June 2013, at 06:49.Content is available under GNU Free Documentation License 1.2.

    o world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server