Hello world/Web server: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(31 intermediate revisions by 19 users not shown)
Line 29:
{{libheader|AWS}}
Uses many defaults, such as 5 max simultaneous connections.
<langsyntaxhighlight lang="ada">
with AWS; use AWS;
with AWS.Response;
Line 49:
Server.Shutdown (TheServer);
end HelloHTTP;
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
Goodbye, world! with random colors and socket polling:
<langsyntaxhighlight lang="aime">void
serve(dispatch w, file s, list colors)
{
Line 86:
 
return 0;
}</langsyntaxhighlight>
Or simply:
<langsyntaxhighlight lang="aime">file i, o, s;
 
tcpip_listen(s, 8080, 0);
Line 98:
"<body><h1>Goodbye, world!</h1></body></html>\n");
f_flush(o);
}</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
VERSION 1: "Hopper" flavour:
<syntaxhighlight lang="amazing hopper">
// Hello world! mode Server
 
#include <hopper.h>
main:
fd=0,fdc=0,message=""
{"HTTP/1.1 200 OK\n","Content-Type: text/html; charset=UTF-8\n\n"}cat
{"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>"},cat
{"<style>body { background-color: #111 },cat
{"h1 { font-size:4cm; text-align: center; color: black; text-shadow: 0 0 2mm red}</style>"}cat
{"</head><body><h1>Goodbye, world!</h1></body></html>\n"}cat,
mov(message)
 
/* Open socket in localhost (by default) */
/* Accept 5 conections (there are also 5 by default, if you put "any weá" there) */
{5,8080}socket (OPENTCPSRV), mov(fd)
 
/* accept conection & send message */
accept(fd), mov(fdc)
{message},send(fdc)
 
/* close all */
{fdc}socket(CLOSESOCK)
{fd}socket(CLOSESOCK)
exit(0)
</syntaxhighlight>
VERSION 2: "Hopper-BASIC" flavour
<syntaxhighlight lang="amazing hopper">
// Hello world! mode Server: desde el navegador, escriba localhost:8080
 
#include <hbasic.h>
Begin
Declare as Numeric (fd,fdc)
as Alpha (message,HEAD,head,body,form,html)
Let ( HEAD := Cat$("HTTP/1.1 200 OK\n","Content-Type: text/html; charset=UTF-8\n\n") + ("<!DOCTYPE html>\n") )
 
ParsNormal$("title","","Bye-bye baby bye-bye")(head)
ParsNormal$("style","","body { background-color: #111 } h1 { font-size:4cm; text-align: center; color: black; text-shadow: 0 0 2mm red}")(head)
ParsNormal$("head","",head)(html)
ParsNormal$("h1","","Goodbye, world!")(body)
ParsNormal$("body","",body)(html)
ParsNormal$("html","",html)(form)
Let( form := Cat$(HEAD,form))
Let( message := Tran$(">\n<","><", form) )
Print( message, Newl)
 
/* Open socket in localhost (by default) */
Let( fd := OpenServerTCP(3,8080) )
 
/* accept conection & send message */
Let( fdc := Accept(fd) )
Send(message,fdc)
 
/* close all */
CloseSocket(fdc)
CloseSocket(fd)
End
</syntaxhighlight>
{{out}}
<pre>Open your browser, and type in the navigation bar: "localhost: 8080": It will show "Goodbye World!" in huge letters and adorable lovecraftian colors!
</pre>
 
=={{header|AntLang}}==
In plain AntLang:
<langsyntaxhighlight AntLanglang="antlang">serv: httprun[8080; {"HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nGoodbye, World!"}]</langsyntaxhighlight>
 
Using ALC:
<langsyntaxhighlight AntLanglang="antlang">load["handlers.ant"]
serv: httprun[8080; {httpwrap["Goodbye, World!"]}]</langsyntaxhighlight>
 
To close the server:
<syntaxhighlight lang AntLang="antlang">kill[serv]</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">serve.port:8080 [ GET "/" -> "Goodbye, World!" ]</syntaxhighlight>
 
{{out}}
 
If you navigate to "localhost:8080" through our web browser, we'll see the message:
 
<pre>Goodbye, World!</pre>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
TCPStartup()
$socket = TCPListen("0.0.0.0",8080)
Line 130 ⟶ 209:
TCPCloseSocket($newConnection)
WEnd
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
Line 137 ⟶ 216:
[http://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html#Primitive-Service]
(Documentation is licensed under GNU Free Documentation License, Version 1.3)
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/gawk -f
BEGIN {
RS = ORS = "\r\n"
Line 151 ⟶ 230:
continue;
close(HttpService)
}</langsyntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<lang qbasic>' Define HTTP constants
Requires BaCon 4.2 or higher.
<syntaxhighlight lang="bacon">' Define HTTP constants
CONST New$ = CHR$(13) & NL$
CONST Sep$ = CHR$(13) & NL$ & CHR$(13) & NL$
Line 165 ⟶ 246:
' Ignore child signals to avoid zombie processes
SIGNAL SIG_IGN, SIGCHLD
 
' Open listening port
OPEN Ip$ & ":8080" FOR SERVER AS mynet
 
' Keep receiving requests
WHILE TRUE
 
' Handle for newly incoming connection
' Open listening port
OPENfd Ip$ & ":8080" FOR SERVER AS= ACCEPT(mynet)
 
' Incoming connection -> create background process
Line 180 ⟶ 264:
' Get the request
REPEAT
RECEIVE dat$ FROM mynetfd
PRINT dat$
UNTIL RIGHT$(dat$, 4) = Sep$
 
' Reply that we're OK
SEND "HTTP/1.1 200 Ok" & New$ & "Content-Length: " & STR$(LEN(Msg$)) & Sep$ & Msg$ TO mynetfd
 
' Close connection
CLOSE SERVER mynetfd
 
' End this process
ENDENDFORK
 
' We are in the parent
ELIF spawn > 0 THEN
 
' Close connection in parent
CLOSE SERVER mynet
 
ENDIF
WEND</syntaxhighlight>
WEND
</lang>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This explicitly supports multiple concurrent connections.
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SOCKLIB"
PROC_initsockets
Line 267 ⟶ 343:
WAIT 0
UNTIL FALSE
END</langsyntaxhighlight>
 
=={{header|C}}==
This is, um, slightly longer than what other languages would be.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 324 ⟶ 400:
close(client_fd);
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight CSharplang="csharp">using System.Text;
using System.Net.Sockets;
using System.Net;
Line 353 ⟶ 429:
}
}
}</langsyntaxhighlight>
{{works with|NancyFX}}<langsyntaxhighlight CSharplang="csharp">namespace Webserver
{
using System;
Line 379 ⟶ 455:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 390 ⟶ 466:
 
File: src/goodbye_world/handler.clj
<langsyntaxhighlight lang="clojure">(ns goodbye-world.handler
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
Line 401 ⟶ 477:
 
(def app
(handler/site app-routes))</langsyntaxhighlight>
 
To start up the server on port 8080, run the following from the project's root:
Line 411 ⟶ 487:
Here's the example with a pre-built server:
 
<langsyntaxhighlight lang="lisp">(ql:quickload :hunchentoot)
(defpackage :hello-web (:use :cl :hunchentoot))
(in-package :hello-web)
Line 417 ⟶ 493:
(define-easy-handler (hello :uri "/") () "Goodbye, World!")
 
(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080)))</langsyntaxhighlight>
 
----
Line 423 ⟶ 499:
Here's an example of doing everything manually
 
<langsyntaxhighlight lang="lisp">(ql:quickload :usocket)
(defpackage :hello-web-manual (:use :cl :usocket))
(in-package :hello-web-manual)
Line 460 ⟶ 536:
(loop for c in connections do (loop while (socket-close c))))))
 
(serve 8080)</langsyntaxhighlight>
 
=={{header|Crystal}}==
 
<langsyntaxhighlight lang="crystal">
require "http/server"
 
server = HTTP::Server.new(8080) do |context|
context.response.print "Goodbye World"
end
 
server.listen(8080)
</syntaxhighlight>
</lang>
 
=={{header|D}}==
Using sockets only, also shows use of heredoc syntax, and std.array.replace, .
''If you copy from this page, be careful with extraneous spaces on the empty lines in the heredoc''.
and casting to bool to satisfy the while conditional.
 
<syntaxhighlight lang="d">import std.socket, std.array;
<lang D>
import std.socket, std.array;
 
ushort port = 8080;
Line 490 ⟶ 565:
Socket currSock;
 
while (cast(bool)null !is (currSock = listener.accept())) {
currSock.sendTo(replace(q"EOF
HTTP/1.1 200 OK
Line 496 ⟶ 571:
 
<html>
<head><title>Hello, world!</title></head>
<body>HelloGoodbye, worldWorld!</body>
</html>
EOF", "\n", "\r\n"));
Line 503 ⟶ 578:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="d">import 'dart:io';
 
main() async {
Line 516 ⟶ 591:
..close();
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program HelloWorldWebServer;
 
{$APPTYPE CONSOLE}
Line 568 ⟶ 643:
lWebServer.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Dylan.NET|Dylan.NET}}==
<syntaxhighlight lang="dylan.net">
<lang Dylan.NET>
//compile with dylan.NET 11.5.1.2 or later!!
#refstdasm "mscorlib.dll"
Line 608 ⟶ 683:
 
end namespace
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Line 615 ⟶ 690:
I fail to see how a longer time will serve any purpose.
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( hello_world_web_server ).
 
Line 637 ⟶ 712:
timer:sleep( 30000 ),
httpd_stop( Pid ).
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">using web
using wisp
 
Line 664 ⟶ 739:
while (true) {} // stay running
}
}</langsyntaxhighlight>
 
=={{header|Fortran}}==
There is no network library in fortran. Use C interoperability and some C compatible library or just start node.js simple web server:
<langsyntaxhighlight lang="fortran">
program http_example
implicit none
Line 683 ⟶ 758:
 
end program http_example
</syntaxhighlight>
</lang>
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">program HelloWorldServer;
{$mode objfpc}{$H+}
uses
Line 727 ⟶ 802:
Serv.Free;
end;
end.</langsyntaxhighlight>
 
 
=={{header|Frink}}==
Frink has a web server platform that runs in a Java servlet container called [https://frinklang.org/fspdocs.html Frink Server Pages] which should be used for real-world applications. However, the following is a simple single-threaded web server for the purposes of this task.
<syntaxhighlight lang="frink">ss = newJava["java.net.ServerSocket", 8080]
while true
{
sock = ss.accept[];
w = new Writer[sock.getOutputStream[]]
w.println["HTTP/1.1 200 OK"]
w.println["Content-Type: text/plain\n"]
w.println["Goodbye, World!"]
w.close[]
}</syntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">native java.io.PrintWriter
native java.net.ServerSocket
 
Line 742 ⟶ 831:
PrintWriter( socket.getOutputStream(), true ).println( 'hello world' )
socket.shutdownOutput()
socket.close()</langsyntaxhighlight>
 
=={{header|Gastona}}==
Line 748 ⟶ 837:
following the server activity and also being able to quit it by closing the window.
But it is not stritctly needed, just the unit #listix# would do the job.
<langsyntaxhighlight lang="gastona">#javaj#
 
<frames> oConsole
Line 761 ⟶ 850:
// Goodbye world!
//</body></html>
</syntaxhighlight>
</lang>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">/**
* Based on https://wiki.gnome.org/Projects/Genie/GIONetworkingSample
* Based on an example of Jezra Lickter http://hoof.jezra.net/snip/nV
Line 839 ⟶ 928:
dos.put_string(response.data)
except e : Error
stderr.printf("%s\n", e.message)</langsyntaxhighlight>
 
{{out}}
Line 850 ⟶ 939:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 864 ⟶ 953:
log.Fatal(http.ListenAndServe(":8080", nil))
}
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
Line 871 ⟶ 960:
using the [http://www.yesodweb.com/book/conduits conduit] stack:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
import Data.ByteString.Char8 ()
Line 879 ⟶ 968:
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"</langsyntaxhighlight>
 
Or using only "standard" features ([http://hackage.haskell.org/package/base base], [http://hackage.haskell.org/package/bytestring bytestring] and [http://hackage.haskell.org/package/network network] from the [http://hackage.haskell.org/platform/ Haskell Platform]):
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
import Data.ByteString.Char8 ()
Line 897 ⟶ 986:
loop s = forever $ forkIO . request . fst =<< accept s
request c = sendAll c response `finally` sClose c
response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"</langsyntaxhighlight>
 
Both works like this:
Line 911 ⟶ 1,000:
Or using warp ([http://hackage.haskell.org/package/warp warp] [https://wiki.haskell.org/Web/Servers#Warp warp example] [http://aosabook.org/en/posa/warp.html about warp]):
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
Line 930 ⟶ 1,019:
index x = responseBuilder status200 [("Content-Type", "text/plain")] $ mconcat $ map copyByteString
[ "Hello World!\n" ]</langsyntaxhighlight>
 
Work like this:
Line 955 ⟶ 1,044:
=={{header|Io}}==
 
<syntaxhighlight lang="io">
<lang io>
WebRequest := Object clone do(
handleSocket := method(aSocket,
Line 971 ⟶ 1,060:
 
WebServer start
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 977 ⟶ 1,066:
would be to [http://www.jsoftware.com/stable.htm download] [http://www.jsoftware.com/docs/help701/user/relhigh.htm j7], edit the jhs script to start on port 8080,
start jhs, visit http://127.0.0.1:8080/jijx then enter the text:
<syntaxhighlight lang ="j">'Goodbye, World!'</langsyntaxhighlight>
This will compute the desired result and display it (actually, it will be displayed twice since the original string will also be displayed).
This would be even simpler if you could just use the default jhs port (65001)...
Line 987 ⟶ 1,076:
For example, here is a web server which ignores the client's request
and always returns Goodbye, World:
<langsyntaxhighlight lang="j">hello=: verb define
8080 hello y NB. try to use port 8080 by default
:
Line 1,013 ⟶ 1,102:
responseFor=: dyad define
'HTTP/1.0 200 OK',CRLF,'Content-Type: text/plain',CRLF,CRLF,'Goodbye, World!',CRLF
)</langsyntaxhighlight>
To deploy this server, once it has been defined, run
<syntaxhighlight lang ="j">hello''</langsyntaxhighlight>
This version works because reasonable http requests fit in a single tcp packet.
(And note that the server waits for one tcp packet before responding.)
Line 1,023 ⟶ 1,112:
Multiple requests will be served in the order that they reach the server,
with a queue size limit of 50 waiting requests imposed by default in the <code>ServerSocket</code> class (may be changed by adding a second positive integer argument to the <code>ServerSocket</code> constructor).
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
Line 1,038 ⟶ 1,127:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,044 ⟶ 1,133:
{{works with|Node.js}}
 
<langsyntaxhighlight lang="javascript">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');</langsyntaxhighlight>
 
It scales:
Line 1,081 ⟶ 1,170:
=={{header|Julia}}==
Requires the HttpServer package to have previously been installed with 'Pkg.add("HttpServer")'
<langsyntaxhighlight Julialang="julia">using HttpServer
server = Server() do req, res
"Goodbye, World!"
end
run(server, 8080)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.io.PrintWriter
import java.net.ServerSocket
 
Line 1,100 ⟶ 1,189:
sock.close()
}
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
Line 1,106 ⟶ 1,195:
here's how you can create a basic multi-threaded webserver
of your own to complete this request:
<langsyntaxhighlight lang="lasso">local(server) = net_tcp
handle => { #server->close }
#server->bind(8080) & listen & forEachAccept => {
Line 1,125 ⟶ 1,214:
#con->writeBytes(bytes(#response))
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
Line 1,131 ⟶ 1,220:
but it's close relative ''Run BASIC'' is designed for serving webpages easily.
The task becomes simply ..
<langsyntaxhighlight lang="lb">print "hello world!" </langsyntaxhighlight>
 
=={{header|Lua}}==
{{works with|lua|5.2.4}}
{{libheader|LuaSocket}}
<langsyntaxhighlight lang="lua">local socket = requestrequire "socket"
local headers = "HTTP/1.1 200 OK\r\nCOntentnContent-Type: text/html; charset=UTF-8\r\nContent-Length: %d\r\n\r\n%s"
local content = "<!doctype html><html><title>Goodbye, World!</title><h1>Goodbye, World!"
local server = assert(socket.bind("localhost", 8080))
Line 1,145 ⟶ 1,234:
client:close()
until not client or not ok
server:close()</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">listener =
SocketListen["127.0.0.1:8080",
Function[{assoc},
Line 1,155 ⟶ 1,244:
"HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"];
Close[client]]]]
SystemOpen["http://127.0.0.1:8080"]</langsyntaxhighlight>
Clean up:
<langsyntaxhighlight Mathematicalang="mathematica">DeleteObject[listener];
Close[listener["Socket"]]</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.37.0}}
<syntaxhighlight lang="min">{
(
{
{"text/plain; charset=utf-8" :content-type} :headers
"Goodbye, World!" :body
}
) :handler
8080 :port
} start-server</syntaxhighlight>
 
=={{header|Modula-2}}==
This is a CGI executable:
<syntaxhighlight lang="text">
MODULE access;
 
Line 1,174 ⟶ 1,275:
WriteLn
END access.
</syntaxhighlight>
</lang>
 
=={{header|NetRexx}}==
{{Trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,215 ⟶ 1,316:
end listener
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import asynchttpserver, asyncdispatch
 
proc cb(req: Request) {.async.} =
Line 1,225 ⟶ 1,326:
asyncCheck newAsyncHttpServer().serve(Port(8080), cb)
runForever()
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Net;
use Concurrency;
Line 1,247 ⟶ 1,348:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
This code is derived from this [http://ocamlunix.forge.ocamlcore.org/sockets.html#htoc54 ocaml-unix documentation].
<langsyntaxhighlight lang="ocaml">let try_finalise f x finally y =
let res = try f x with e -> finally y; raise e in
finally y;
Line 1,307 ⟶ 1,408:
 
let _ =
Unix.handle_unix_error server ()</langsyntaxhighlight>
 
=={{header|Ol}}==
This sample sends 200 OK on any request and echoes the request headers.
<langsyntaxhighlight lang="ol">(import (lib http))
 
(http:run 8080 (lambda (fd request headers send close)
Line 1,325 ⟶ 1,426:
(close #t)
))
</syntaxhighlight>
</lang>
 
=={{header|Opa}}==
From [http://doc.opalang.org/index.html#_a_first_peek_at_opa Opa documentation]:
<langsyntaxhighlight lang="ocaml">server = one_page_server("Hello", -> <>Goodbye, world</>)</langsyntaxhighlight>
Compile and run:
<syntaxhighlight lang ="bash">opa file.opa --</langsyntaxhighlight>
 
=={{header|Panda}}==
Using the command line client. Listen to port 8080. For each request a request object is returned, we ignore this and just use it to send message which will be the response.
 
<langsyntaxhighlight lang="panda">8080.port.listen.say("Hello world!")</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">use Socket;
 
my $port = 8080;
Line 1,363 ⟶ 1,464:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close CLIENT;
}</langsyntaxhighlight>
Various modules exist for using sockets, including the popular IO::Socket
which provides a simpler and more friendly OO interface for the socket layer.
Here is the solution using this module:
{{libheader|IO::Socket::INET}}
<langsyntaxhighlight Perllang="perl">use IO::Socket::INET;
 
my $sock = new IO::Socket::INET ( LocalAddr => "127.0.0.1:8080",
Line 1,379 ⟶ 1,480:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close $client;
}</langsyntaxhighlight>
 
Using Perl's glue power, provide a suicide note
with visitor counter via netcat:
<langsyntaxhighlight Perllang="perl">while (++(our $vn)) {
open NC, "|-", qw(nc -l -p 8080 -q 1);
print NC "HTTP/1.0 200 OK\xd\xa",
"Content-type: text/plain; charset=utf-8\xdx0d\xax0a\xdx0d\xax0a",
"Goodbye, World! (hello, visitor No. $vn!)\xdx0d\xax0a";
}</langsyntaxhighlight>
 
Here's another solution using Plack (may be found on CPAN):
<langsyntaxhighlight Perllang="perl">use Plack::Runner;
my $app = sub {
return [ 200,
Line 1,400 ⟶ 1,501:
my $runner = Plack::Runner->new;
$runner->parse_options('--host' => 'localhost', '--port' => 8080);
$runner->run($app);</langsyntaxhighlight>
 
When using plackup, then this may be compressed to one line:
<langsyntaxhighlight lang="perl">my $app = sub { return [ 200, [ 'Content-Type' => 'text/html; charset=UTF-8' ], [ '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>' ] ] };</langsyntaxhighlight>
Use <langsyntaxhighlight Shelllang="shell">plackup --host localhost --port 8080 script.psgi</langsyntaxhighlight> to start the webserver.
 
=={{header|Phix}}==
Windows only for now (should be relatively straightforward to get it working on linux)<br>
Output as C, code is however a translation of a FASM example.
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>-- demo\rosetta\SimpleHttpServer.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\SimpleHttpServer.exw</span>
include builtins\sockets.e -- added for 0.8.1 (not yet documented)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">sockets</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">MAX_QUEUE</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">ESCAPE</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#1B</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">response</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"""
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Bye-bye baby bye-bye&lt;/title&gt;
&lt;style&gt;
body { background-color: #111 }
h1 { font-size:4cm; text-align: center; color: black;
text-shadow: 0 0 2mm red}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Goodbye, world!&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;
"""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\r\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"server started, open http://localhost:8080/ in browser or curl, press Esc or Q to quit\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">sock</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">socket</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AF_INET</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SOCK_STREAM</span><span style="color: #0000FF;">,</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pSockAddr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sockaddr_in</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AF_INET</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8080</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">bind</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pSockAddr</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SOCKET_ERROR</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"bind (%v)"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_socket_error</span><span style="color: #0000FF;">()})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">listen</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">,</span><span style="color: #000000;">MAX_QUEUE</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">SOCKET_ERROR</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"listen (%v)"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_socket_error</span><span style="color: #0000FF;">()})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">(),{</span><span style="color: #000000;">ESCAPE</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'q'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'Q'</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">code</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">select</span><span style="color: #0000FF;">({</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">},{},{},</span><span style="color: #000000;">250000</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (0.25s)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">code</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SOCKET_ERROR</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"select (%v)"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">get_socket_error</span><span style="color: #0000FF;">()})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">code</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (not timeout)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">peer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">accept</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">ip</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getsockaddr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peer</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">request</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">recv</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Client IP: %s\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">ip_to_string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ip</span><span style="color: #0000FF;">),</span><span style="color: #000000;">request</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">request</span><span style="color: #0000FF;">)></span><span style="color: #000000;">3</span> <span style="color: #008080;">and</span> <span style="color: #000000;">request</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">"GET "</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">bytes_sent</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">send</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">response</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d bytes successfully sent\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bytes_sent</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">shutdown</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">SD_SEND</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- tell curl it's over</span>
<span style="color: #000000;">peer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">closesocket</span><span style="color: #0000FF;">(</span><span style="color: #000000;">peer</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (as does this)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">sock</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">closesocket</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sock</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">WSACleanup</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{Out}}
Server console, once you have opened http://localhost:8080 in your browser, or run curl http://localhost:8080
<pre>
server started, open http://localhost:8080/ in browser or curl, press Esc or Q to quit
Client IP: 127.0.0.1
GET / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.55.1
Accept: */*
 
352 bytes successfully sent
constant MAX_QUEUE = 100,
</pre>
ESCAPE = #1B,
BUFFER_SIZE = 2048,
buffer = allocate(BUFFER_SIZE),
sock_addr = new_sock_addr(AF_INET, 8080, NULL),
peerAddr = new_sock_addr(),
 
response = substitute("""
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
 
<!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>
 
""","\n","\r\n")
 
atom sock = socket(AF_INET,SOCK_STREAM,NULL)
bind(sock,sock_addr)
listen(sock,MAX_QUEUE)
while get_key()!=ESCAPE do
atom peer = accept(sock,peerAddr),
ip = get_sin_addr(sock_addr)
integer len = recv(peer,buffer,BUFFER_SIZE,0)
string request = peek({buffer,len})
printf(1,"Client IP: %s\n%s\n",{ip_to_string(ip),request})
if length(request)>3 and request[1..4]="GET " then
poke(buffer,response)
send(peer,buffer,length(response),0)
end if
end while</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
// AF_INET6 for IPv6 // IP
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
Line 1,475 ⟶ 1,594:
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Contents of the file "goodbye.l":
<langsyntaxhighlight PicoLisplang="picolisp">(html 0 "Bye" NIL NIL
"Goodbye, World!" )</langsyntaxhighlight>
Start server:
<pre>$ pil @lib/http.l @lib/xhtml.l -'server 8080 "goodbye.l"' -wait</pre>
Line 1,486 ⟶ 1,605:
=={{header|Pike}}==
 
<syntaxhighlight lang="pike">
<lang Pike>
void handle_request(Protocols.HTTP.Server.Request request)
{
Line 1,498 ⟶ 1,617:
return -1; // -1 is a special case that retirns control to the backend
}
</syntaxhighlight>
</lang>
 
=={{header|Pony}}==
Using only in-built TCP listeners, not the HTTP server package
<syntaxhighlight lang="pony">
use "net"
 
actor Main
new create(env: Env) =>
try TCPListener(env.root as AmbientAuth,
Listener,
"127.0.0.1", "8080")
else env.err.print("unable to use the network")
end
 
// Boilerplate code, create a TCP listener on a socket
class Listener is TCPListenNotify
 
new iso create() => None
 
fun ref listening(_: TCPListener ref) => None
 
fun ref not_listening(listen: TCPListener ref) => listen.close()
 
fun ref connected(listen: TCPListener ref): TCPConnectionNotify iso^ =>
Server
 
 
// HTTP server that handles the TCP connections
class val Server is TCPConnectionNotify
 
// Empty ctor
new iso create() => None
 
// Impl for when server accepts the client request
fun accepted(_: TCPConnection ref) => None
 
// Impl for when server receives client data
fun ref received(conn: TCPConnection ref, _: Array[U8] iso, _: USize)
: Bool
=>
// handle request
conn.write("HTTP/1.1 200 OK\r\n\r\n")
conn.write("<html><body><p>")
conn.write("Goodbye, World!")
conn.write("</p></body></html>")
conn.dispose()
false
 
// Impl for when client closes the connection
fun ref closed(conn: TCPConnection ref) => conn.dispose()
 
// Impl for when client fails to connect to all possible addresses for the server
fun ref connect_failed(_: TCPConnection ref) => None
</syntaxhighlight>
 
=={{header|Prolog}}==
Line 1,504 ⟶ 1,677:
{{works with|YAP}}
 
<langsyntaxhighlight Prologlang="prolog">% 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)).
Line 1,521 ⟶ 1,694:
% wrapped in <h1></h1> tags, "Goodbye, World!".
say_goodbye(_Request) :- reply_html_page([title('Howdy')],
[h1('Goodbye, World!')]).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">If InitNetwork() = 0
MessageRequester("Error", "Can't initialize the network !")
End
Line 1,546 ⟶ 1,719:
Else
MessageRequester("Error", "Can't create the server (port in use ?).")
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Using the <code>wsgiref.simple_server</code> module (Python < 3.2).
 
<langsyntaxhighlight Pythonlang="python">from wsgiref.simple_server import make_server
 
def app(environ, start_response):
Line 1,558 ⟶ 1,731:
 
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()</langsyntaxhighlight>
 
Using the <code>http.server</code> module (Python 3).
 
<langsyntaxhighlight Pythonlang="python">import threading
 
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Line 1,597 ⟶ 1,770:
except KeyboardInterrupt:
pass
</syntaxhighlight>
</lang>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
library(httpuv)
 
Line 1,612 ⟶ 1,785:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="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 "/")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo}}
<syntaxhighlight lang="raku" perl6line>my $listen = IO::Socket::INET.new(:listen, :localhost<localhost>, :localport(8080));
loop {
my $conn = $listen.accept;
Line 1,632 ⟶ 1,805:
$conn.print: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n";
$conn.close;
}</langsyntaxhighlight>
Async:
<syntaxhighlight lang="raku" perl6line>react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply.lines -> $line {
Line 1,641 ⟶ 1,814:
}
}
}</langsyntaxhighlight>
 
=={{header|REALbasic}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Class HTTPSock
Inherits TCPSocket
Line 1,678 ⟶ 1,851:
End Sub
End Class
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Based on the UNIX Shell entry. Works with Regina, tested on GNU/Linux. Requires netcat as nc.
 
<langsyntaxhighlight lang="rexx">/* HTTP hello server */
response.1 = 'HTTP/1.1 200 OK' || '0D0A'X,
|| 'Connection: close' || '0D0A'X,
Line 1,694 ⟶ 1,867:
DO FOREVER
ADDRESS SYSTEM 'nc -l 8080' WITH INPUT STEM response.
END</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 1,755 ⟶ 1,928:
close()
}
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Using the WEBrick module from Ruby's standard library.
<langsyntaxhighlight lang="ruby">require 'webrick'
server = WEBrick::HTTPServer.new(:Port => 8080)
server.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
trap("INT") {server.shutdown}
server.start</langsyntaxhighlight>
 
Same code without <code>trap</code>, in a single statement using <code>tap</code>.
<langsyntaxhighlight Rubylang="ruby">require 'webrick'
WEBrick::HTTPServer.new(:Port => 80).tap {|srv|
srv.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
}.start</langsyntaxhighlight>
 
Using the [http://www.sinatrarb.com/ sinatra] gem:
<langsyntaxhighlight lang="ruby">require 'sinatra'
get("/") { "Goodbye, World!" }</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">html "Hello World!"</langsyntaxhighlight>
 
=={{header|Rust}}==
Basically no error handling. This web server will simply panic if there is any sort of error.
<langsyntaxhighlight lang="rust">use std::net::{Shutdown, TcpListener};
use std::thread;
use std::io::Write;
Line 1,807 ⟶ 1,980:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Rye}}==
<syntaxhighlight lang="clojure">rye .needs { http }
 
new-server ":8080"
|handle "/" fn { r w } { write w "Goodbye, World!" }
|serve</syntaxhighlight>
 
=={{header|Salmon}}==
<langsyntaxhighlight Salmonlang="salmon">use "http.salm" : "http.si";
 
/* Don't do any logging. */
Line 1,816 ⟶ 1,996:
 
simple_http_server(8080, procedure(header, connection)
{ respond_text(connection, "Goodbye, World!"); });</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
{{Trans|Java}}It shows that Scala can simply embed XML fragments.
<langsyntaxhighlight Scalalang="scala">import java.io.PrintWriter
import java.net.ServerSocket
 
Line 1,844 ⟶ 2,024:
sock.close()
}
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
The code below was inspired by the example code for the function [http://seed7.sourceforge.net/libraries/listener.htm#openInetListener%28in_integer%29 openInetListener].
 
<langsyntaxhighlight Seed7lang="seed7">$ include "seed7_05.s7i";
include "listener.s7i";
 
Line 1,867 ⟶ 2,047:
close(sock);
end while;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
 
Using the low-level ''Socket'' object:
<langsyntaxhighlight lang="ruby">var port = 8080;
var protocol = Socket.getprotobyname("tcp");
 
Line 1,895 ⟶ 2,075:
"<body>Goodbye, world!</body></html>\r\n");
client.close;
}</langsyntaxhighlight>
 
A more friendly interface, using the ''IO::Socket::INET'' library:
<langsyntaxhighlight lang="ruby">var inet = require('IO::Socket::INET');
 
var sock = inet.new( LocalAddr => "127.0.0.1:8080",
Line 1,911 ⟶ 2,091:
"<body>Goodbye, world!</body></html>\r\n");
client.close;
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
starting server:
<langsyntaxhighlight lang="smalltalk">Smalltalk loadPackage:'stx:goodies/webServer'. "usually already loaded"
|myServer service|
 
Line 1,929 ⟶ 2,109:
service linkNames:#('/' ).
service registerServiceOn: myServer.
myServer start.</langsyntaxhighlight>
Be aware that the above is an ad-hoc minimal scripting example.
Normally, a service subclass is used and
Line 1,941 ⟶ 2,121:
that includes a ZnServer class.
Here's the simplest solution to start a web server:
<langsyntaxhighlight lang="smalltalk">(ZnServer startDefaultOn: 1701)
onRequestRespond: [ :request |
ZnResponse ok: (ZnEntity text: 'Hello World!') ].</langsyntaxhighlight>
 
To stop the server, use the following:
<syntaxhighlight lang ="smalltalk">ZnServer stopDefault.</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world!" ) ;
 
Line 1,977 ⟶ 2,157:
end handle x => (Socket.close listener; raise x)
;
</syntaxhighlight>
</lang>
call - smlnj interpreter
- serve (INetSock.TCP.socket()) 8080 ;
Line 1,995 ⟶ 2,175:
===Tcl 8.x===
This version is adapted from [http://wiki.tcl.tk/28414 the Tcler's Wiki].
<langsyntaxhighlight lang="tcl">proc accept {chan addr port} {
while {[gets $chan] ne ""} {}
puts $chan "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n"
Line 2,002 ⟶ 2,182:
}
socket -server accept 8080
vwait forever</langsyntaxhighlight>
 
===Jim Tcl===
Jim is a small footprint reimplementation of Tcl with modern features.
<langsyntaxhighlight lang="tcl">set s [socket stream.server 127.0.0.1:8080]
$s readable {
set client [$s accept]
Line 2,013 ⟶ 2,193:
$client close
}
vwait done</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="bash">while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; echo 'Hello, World!'; } | nc -l 8080; done</langsyntaxhighlight>
 
=={{header|Wart}}==
 
<langsyntaxhighlight lang="python">with server_socket socket :port 4000
accepting client :from socket
making stdout outfile+fd.client
Line 2,027 ⟶ 2,207:
prn "Content-type: text/plain"
prn ""
prn "Hello, world!"</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|SpiderWren}}
<syntaxhighlight lang="wren">import "web" for Routes, App
 
Routes.GET("/") {
return "Goodbye, World!"
}
 
App.run(8080)</syntaxhighlight>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
This SHOULD assemble on both Linux and Windows.
(Tested on Arch, Don't have windows installed atm :[)
<syntaxhighlight lang="asm">
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Crossplatform(?) Web Server example using UASM's OO Language extention
;;
;; Linux Build:
;; $ uasm -elf64 websrv.asm
;; $ gcc -o websrv websrv.o -no-pie
;; With MUSL libc
;; $ musl-gcc -o websrv websrv.o -e main -nostartfiles -no-pie
;;
;; Windows Build:
;; $ uasm64 -win64 websrv.asm
;; $ link /machine:x64 /subsystem:console /release websrv.obj
;; kernel32.lib msvcrt.lib ws2_32.lib
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
option casemap:none
option literals:on ;; Usually on by default buuuuuut...
 
WIN64 equ 1
LIN64 equ 3
 
 
ifndef __WEBSRV_CLASS__
__WEBSERV_CLASS__ equ 1
 
AF_INET equ 2
SOCK_STREAM equ 1
INADDR_ANY equ 0
 
in_addr struct
s_addr dd ?
in_addr ends
 
sockaddr struct
sa_family dw ?
sa_data db 14 dup (?)
sockaddr ends
 
sockaddr_in struct
sin_family dw ?
sin_port dw ?
sin_addr in_addr <?>
sin_zero db 8 dup (?)
sockaddr_in ends
 
WSADATA struct
wVersion dw ?
wHighVersion dw ?
iMaxSockets dw ?
iMaxUdpDg dw ?
szDescription db 256 dup (?)
szSystemStatus db 128 dup (?)
lpVendorInfo dq ?
WSADATA ends
;; Platform specific requirements etc..
if @Platform eq WIN64
;;include/includelibs can be used here. But this works too.
option dllimport:<kernel32>
ExitProcess proto ucode:dword
HeapAlloc proto fd:qword, flgs:dword, hlen:qword
HeapFree proto fd:qword, flgs:dword, lpmem:qword
GetProcessHeap proto
option dllimport:<msvcrt>
printf proto fmt:qword, args:VARARG
strlen proto buff:qword
option dllimport:<ws2_32>
WSAStartup proto ver:word, wsa:qword
WSACleanup proto wsa:qword
closesocket proto fd:dword
socket proto d:dword, s:dword, prtl:dword
bind proto fd:dword, saddr:qword, slen:dword
listen proto fd:dword, blog:dword
accept proto fd:dword, caddr:qword, slen:qword
send proto fd:dword, buff:qword, blen:dword, flgs:dword
option dllimport:none
exit equ ExitProcess
close equ closesocket
elseif @Platform eq LIN64
;; Required proto from Libc stuff.
malloc proto SYSTEMV mem:qword ;; Required by the class macros.
free proto SYSTEMV mem:qword ;; It uses HeapAlloc on windows.
printf proto SYSTEMV fmt:qword, args:VARARG
strlen proto SYSTEMV buff:qword
socket proto SYSTEMV d:dword, s:dword, prtl:dword
bind proto SYSTEMV fd:dword, saddr:qword, slen:dword
listen proto SYSTEMV fd:dword, blog:dword
accept proto SYSTEMV fd:dword, saddr:qword, slen:qword
send proto SYSTEMV fd:dword, buff:qword, blen:dword, flgs:dword
close proto SYSTEMV fd:dword
exit proto SYSTEMV uexit:dword
else
;; Could do some OSX or w/e specific crap, but I don't use
;; a Mac so, I dunno shit about it's API :]
endif
 
;; Class definitions etc..
CLASS websrv
;; Class Method definitions
CMETHOD serve
ENDMETHODS
;; Class Variables.
if @Platform eq WIN64
wsa WSADATA <?>
endif
tmpl db "[websrv->%s] - %s",10,0
http db "HTTP/1.1 200 OK",13,10,
"Content-Type: text/html; charset=UTF-8",13,10,13,10,
"<html><head><title>Goodbye</title></head><body>Goodbye, World!</body></html>",0
sock dd 0
port dw 8080
ENDCLASS
pwebsrv typedef ptr websrv
 
;; Method implementation..
; Syntax:
; METHOD ClassName, MethodName, <ReturnType>, <USE extra regs for ret>, args..
METHOD websrv, Init, <VOIDARG>, <>
local x:sockaddr_in
 
mov rbx, thisPtr ;; Force the ThisPtr reference reg to be RBX 'cause of windoze
assume rbx:ptr websrv ;; its default is RCX, and RDI on linux. *shrugs*
invoke printf, addr [rbx].tmpl,CSTR("init"), CSTR("Starting...")
if @Platform eq WIN64
invoke WSAStartup, 200h, addr [rbx].wsa
endif
invoke socket, AF_INET, SOCK_STREAM, 0
.if rax == -1
invoke printf, addr [rbx].tmpl, CSTR("init:ERROR"), CSTR("Socket() returned < 0")
mov rax, rbx
ret
.endif
mov [rbx].sock, eax
invoke printf, CSTR("[websrv->init:socket] - %d",10), eax
mov x.sin_family, AF_INET
mov x.sin_addr.s_addr, INADDR_ANY
mov ax, [rbx].port
xchg al,ah
mov x.sin_port, ax
invoke bind, [rbx].sock, addr x, sizeof(x)
.if eax == -1
invoke printf, addr [rbx].tmpl, CSTR("init:ERROR") , CSTR("Bind failed.")
xor eax, eax
mov [rbx].sock, 0
mov rax, rbx
ret
.endif
invoke printf, addr [rbx].tmpl, CSTR("init"), CSTR("Bind successful.")
mov rax, rbx
assume rbx: nothing
ret
ENDMETHOD
 
METHOD websrv, serve, <VOIDARG>, <>
local tmp:qword
local cfd:dword
local x:sockaddr
 
mov rbx, thisPtr
assume rbx:ptr websrv
.if [rbx].sock == 0
ret
.endif
invoke printf, addr [rbx].tmpl,CSTR("serve"), CSTR("Listening for incomming connections")
invoke listen, [rbx].sock, 5
.if rax == -1
invoke printf, addr [rbx].tmpl, CSTR("serve:ERROR"), CSTR("Listen() returned -1")
ret
.endif
 
.while(1)
mov tmp, sizeof(x)
invoke accept, [rbx].sock, addr x, addr tmp
.if eax == -1
invoke printf, addr [rbx].tmpl, CSTR("serve:ERROR"), CSTR("Accept() returned -1")
ret
.endif
mov cfd, eax
invoke printf, addr [rbx].tmpl, CSTR("serve"), CSTR("Connection established.")
invoke strlen, addr [rbx].http
invoke send, cfd, addr [rbx].http, eax , 0
invoke close, cfd
.endw
assume rbx:nothing
ret
ENDMETHOD
 
METHOD websrv, Destroy, <VOIDARG>, <>
mov rbx, thisPtr
assume rbx:ptr websrv
invoke printf, addr [rbx].tmpl,CSTR("destroy"), CSTR("Calling Close and exit.")
invoke close, [rbx].sock
if @Platform eq WIN64
invoke WSACleanup, addr [rbx].wsa
endif
assume rbx:nothing
invoke exit, 0
ret
ENDMETHOD
endif ;; __WEBSRV_CLASS__
 
;; Start of main run code...
.code
main proc
local server:ptr websrv
 
mov server, _NEW(websrv)
server->serve()
_DELETE(server)
ret
main endp
end
</syntaxhighlight>
 
=={{header|zkl}}==
A threaded web server that returns "Goodbye, World!" for every request
<langsyntaxhighlight lang="zkl">const PORT=8080;
const SERVLET_THREADS=4;
 
Line 2,076 ⟶ 2,486:
println("HTTP server started at http://",
serverSocket.hostname, ":", serverSocket.port);
serverSocket.listen(jobPipe);</langsyntaxhighlight>
9,476

edits