Hello World/Web Server - Rosetta Code
Total Page:16
File Type:pdf, Size:1020Kb
Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server Hello world/Web server From Rosetta Code < Hello world The browser is the new GUI! Hello world/Web The task is to serve our standard text "Goodbye, World!" to server http://localhost:8080/ so that it can be viewed with a web browser. You are The provided solution must start or implement a server that accepts encouraged to multiple client connections and serves text as requested. solve this task according to the task description, Note that starting a web browser or opening a new window with using any language you this URL is not part of the task. Additionally, it is permissible to may know. serve the provided page as a plain text file (there is no requirement to serve properly formatted HTML here). The browser will generally do the right thing with simple text like this. Contents 1 Ada 2 AWK 3 BBC BASIC 4 C 5 C++ 6 C# 7 D 8 Delphi 9 Dylan.NET 10 Erlang 11 Fantom 12 Go 13 Haskell 14 Io 15 J 16 Java 17 JavaScript 18 Liberty BASIC 19 Modula-2 20 NetRexx 21 Objeck 22 OCaml 23 Opa 24 Perl 25 Perl 6 26 PicoLisp 27 Prolog 28 PureBasic 29 PHP 30 Python 1 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server 31 Racket 32 REALbasic 33 Ruby 34 Run BASIC 35 Salmon 36 Seed7 37 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. Data is 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 from here [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 = "<HTML><HEAD>" \ "<TITLE>A Famous Greeting</TITLE></HEAD>" \ "<BODY><H1>Hello, world</H1></BODY></HTML>" 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 2 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server 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%), "<html><head><title>Hello World!</title></head>") IF FN_writelinesocket(sock%(i%), "<body><h1>Hello World!</h1>") IF FN_writelinesocket(sock%(i%), "</body></html>") 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 <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> 3 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response [] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<doctype !html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\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 { static void Main (string [] args ) { const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n"; const int port = 8080 ; bool serverRunning = true ; TcpListener tcpListener = new TcpListener (IPAddress.Any , port ); tcpListener.Start (); 4 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server 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 to satisfy 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 <html> <head><title>Hello, world!</title></head> <body>Hello, world!</body> </html> 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 ; 5 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server 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"<html>\n<body>\nGoodbye, world!\n</body>\n</html>\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_Length()) 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. 6 sur 18 19/07/2013 19:57 Hello world/Web server - Rosetta Code http://rosettacode.org/wiki/Hello_world/Web_server