Hello world/Web server: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Phix}}: added syntax colouring the hard way) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(22 intermediate revisions by 15 users not shown) | |||
Line 29:
{{libheader|AWS}}
Uses many defaults, such as 5 max simultaneous connections.
<
with AWS; use AWS;
with AWS.Response;
Line 49:
Server.Shutdown (TheServer);
end HelloHTTP;
</syntaxhighlight>
=={{header|Aime}}==
Goodbye, world! with random colors and socket polling:
<
serve(dispatch w, file s, list colors)
{
Line 86:
return 0;
}</
Or simply:
<
tcpip_listen(s, 8080, 0);
Line 98:
"<body><h1>Goodbye, world!</h1></body></html>\n");
f_flush(o);
}</
=={{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:
<
Using ALC:
<
serv: httprun[8080; {httpwrap["Goodbye, World!"]}]</
To close the server:
<syntaxhighlight lang
=={{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">
TCPStartup()
$socket = TCPListen("0.0.0.0",8080)
Line 130 ⟶ 209:
TCPCloseSocket($newConnection)
WEnd
</syntaxhighlight>
=={{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)
<
BEGIN {
RS = ORS = "\r\n"
Line 151 ⟶ 230:
continue;
close(HttpService)
}</
=={{header|
==={{header|BaCon}}===
Requires BaCon 4.2 or higher.
<
CONST New$ = CHR$(13) & NL$
CONST Sep$ = CHR$(13) & NL$ & CHR$(13) & NL$
Line 197 ⟶ 277:
ENDFORK
ENDIF
WEND</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This explicitly supports multiple concurrent connections.
<
PROC_initsockets
Line 263 ⟶ 343:
WAIT 0
UNTIL FALSE
END</
=={{header|C}}==
This is, um, slightly longer than what other languages would be.
<
#include <stdlib.h>
#include <unistd.h>
Line 320 ⟶ 400:
close(client_fd);
}
}</
=={{header|C sharp|C#}}==
<
using System.Net.Sockets;
using System.Net;
Line 349 ⟶ 429:
}
}
}</
{{works with|NancyFX}}<
{
using System;
Line 375 ⟶ 455:
}
}
}</
=={{header|C++}}==
Line 386 ⟶ 466:
File: src/goodbye_world/handler.clj
<
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
Line 397 ⟶ 477:
(def app
(handler/site app-routes))</
To start up the server on port 8080, run the following from the project's root:
Line 407 ⟶ 487:
Here's the example with a pre-built server:
<
(defpackage :hello-web (:use :cl :hunchentoot))
(in-package :hello-web)
Line 413 ⟶ 493:
(define-easy-handler (hello :uri "/") () "Goodbye, World!")
(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080)))</
----
Line 419 ⟶ 499:
Here's an example of doing everything manually
<
(defpackage :hello-web-manual (:use :cl :usocket))
(in-package :hello-web-manual)
Line 456 ⟶ 536:
(loop for c in connections do (loop while (socket-close c))))))
(serve 8080)</
=={{header|Crystal}}==
<
require "http/server"
server = HTTP::Server.new
context.response.print "Goodbye World"
end
server.listen(8080)
</syntaxhighlight>
=={{header|D}}==
Using sockets only, also shows use of heredoc syntax
''If you copy from this page, be careful with extraneous spaces on the empty lines in the heredoc''.
<syntaxhighlight lang="d">import std.socket, std.array;
ushort port = 8080;
Line 486 ⟶ 565:
Socket currSock;
while (
currSock.sendTo(replace(q"EOF
HTTP/1.1 200 OK
Line 492 ⟶ 571:
<html>
<head><title>Hello
<body>
</html>
EOF", "\n", "\r\n"));
Line 499 ⟶ 578:
}
}
</syntaxhighlight>
=={{header|Dart}}==
<
main() async {
Line 512 ⟶ 591:
..close();
}
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 564 ⟶ 643:
lWebServer.Free;
end;
end.</
=={{header|Dylan.NET|Dylan.NET}}==
<syntaxhighlight lang="dylan.net">
//compile with dylan.NET 11.5.1.2 or later!!
#refstdasm "mscorlib.dll"
Line 604 ⟶ 683:
end namespace
</syntaxhighlight>
=={{header|Erlang}}==
Line 611 ⟶ 690:
I fail to see how a longer time will serve any purpose.
<syntaxhighlight lang="erlang">
-module( hello_world_web_server ).
Line 633 ⟶ 712:
timer:sleep( 30000 ),
httpd_stop( Pid ).
</syntaxhighlight>
=={{header|Fantom}}==
<
using wisp
Line 660 ⟶ 739:
while (true) {} // stay running
}
}</
=={{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:
<
program http_example
implicit none
Line 679 ⟶ 758:
end program http_example
</syntaxhighlight>
=={{header|Free Pascal}}==
<
{$mode objfpc}{$H+}
uses
Line 723 ⟶ 802:
Serv.Free;
end;
end.</
=={{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}}==
<
native java.net.ServerSocket
Line 738 ⟶ 831:
PrintWriter( socket.getOutputStream(), true ).println( 'hello world' )
socket.shutdownOutput()
socket.close()</
=={{header|Gastona}}==
Line 744 ⟶ 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.
<
<frames> oConsole
Line 757 ⟶ 850:
// Goodbye world!
//</body></html>
</syntaxhighlight>
=={{header|Genie}}==
<
* Based on https://wiki.gnome.org/Projects/Genie/GIONetworkingSample
* Based on an example of Jezra Lickter http://hoof.jezra.net/snip/nV
Line 835 ⟶ 928:
dos.put_string(response.data)
except e : Error
stderr.printf("%s\n", e.message)</
{{out}}
Line 846 ⟶ 939:
=={{header|Go}}==
<
import (
Line 860 ⟶ 953:
log.Fatal(http.ListenAndServe(":8080", nil))
}
</syntaxhighlight>
=={{header|Haskell}}==
Line 867 ⟶ 960:
using the [http://www.yesodweb.com/book/conduits conduit] stack:
<
import Data.ByteString.Char8 ()
Line 875 ⟶ 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"</
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]):
<
import Data.ByteString.Char8 ()
Line 893 ⟶ 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"</
Both works like this:
Line 907 ⟶ 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]):
<
import Network.Wai
Line 926 ⟶ 1,019:
index x = responseBuilder status200 [("Content-Type", "text/plain")] $ mconcat $ map copyByteString
[ "Hello World!\n" ]</
Work like this:
Line 951 ⟶ 1,044:
=={{header|Io}}==
<syntaxhighlight lang="io">
WebRequest := Object clone do(
handleSocket := method(aSocket,
Line 967 ⟶ 1,060:
WebServer start
</syntaxhighlight>
=={{header|J}}==
Line 973 ⟶ 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
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 983 ⟶ 1,076:
For example, here is a web server which ignores the client's request
and always returns Goodbye, World:
<
8080 hello y NB. try to use port 8080 by default
:
Line 1,009 ⟶ 1,102:
responseFor=: dyad define
'HTTP/1.0 200 OK',CRLF,'Content-Type: text/plain',CRLF,CRLF,'Goodbye, World!',CRLF
)</
To deploy this server, once it has been defined, run
<syntaxhighlight lang
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,019 ⟶ 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).
<
import java.io.PrintWriter;
import java.net.ServerSocket;
Line 1,034 ⟶ 1,127:
}
}
}</
=={{header|JavaScript}}==
Line 1,040 ⟶ 1,133:
{{works with|Node.js}}
<
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:
Line 1,077 ⟶ 1,170:
=={{header|Julia}}==
Requires the HttpServer package to have previously been installed with 'Pkg.add("HttpServer")'
<
server = Server() do req, res
"Goodbye, World!"
end
run(server, 8080)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.net.ServerSocket
Line 1,096 ⟶ 1,189:
sock.close()
}
}</
=={{header|Lasso}}==
Line 1,102 ⟶ 1,195:
here's how you can create a basic multi-threaded webserver
of your own to complete this request:
<
handle => { #server->close }
#server->bind(8080) & listen & forEachAccept => {
Line 1,121 ⟶ 1,214:
#con->writeBytes(bytes(#response))
}
}</
=={{header|Liberty BASIC}}==
Line 1,127 ⟶ 1,220:
but it's close relative ''Run BASIC'' is designed for serving webpages easily.
The task becomes simply ..
<
=={{header|Lua}}==
{{works with|lua|5.2.4}}
{{libheader|LuaSocket}}
<
local headers = "HTTP/1.1 200 OK\r\nContent-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!"
Line 1,141 ⟶ 1,234:
client:close()
until not client or not ok
server:close()</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
SocketListen["127.0.0.1:8080",
Function[{assoc},
Line 1,151 ⟶ 1,244:
"HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"];
Close[client]]]]
SystemOpen["http://127.0.0.1:8080"]</
Clean up:
<
Close[listener["Socket"]]</
=={{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,170 ⟶ 1,275:
WriteLn
END access.
</syntaxhighlight>
=={{header|NetRexx}}==
{{Trans|Java}}
<
options replace format comments java crossref symbols binary
Line 1,211 ⟶ 1,316:
end listener
return
</syntaxhighlight>
=={{header|Nim}}==
<
proc cb(req: Request) {.async.} =
Line 1,221 ⟶ 1,326:
asyncCheck newAsyncHttpServer().serve(Port(8080), cb)
runForever()
</syntaxhighlight>
=={{header|Objeck}}==
<
use Net;
use Concurrency;
Line 1,243 ⟶ 1,348:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
This code is derived from this [http://ocamlunix.forge.ocamlcore.org/sockets.html#htoc54 ocaml-unix documentation].
<
let res = try f x with e -> finally y; raise e in
finally y;
Line 1,303 ⟶ 1,408:
let _ =
Unix.handle_unix_error server ()</
=={{header|Ol}}==
This sample sends 200 OK on any request and echoes the request headers.
<
(http:run 8080 (lambda (fd request headers send close)
Line 1,321 ⟶ 1,426:
(close #t)
))
</syntaxhighlight>
=={{header|Opa}}==
From [http://doc.opalang.org/index.html#_a_first_peek_at_opa Opa documentation]:
<
Compile and run:
<syntaxhighlight lang
=={{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.
<
=={{header|Perl}}==
<
my $port = 8080;
Line 1,359 ⟶ 1,464:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close CLIENT;
}</
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}}
<
my $sock = new IO::Socket::INET ( LocalAddr => "127.0.0.1:8080",
Line 1,375 ⟶ 1,480:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close $client;
}</
Using Perl's glue power, provide a
with visitor counter via netcat:
<
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\
"Goodbye, World! (hello, visitor No. $vn!)\
}</
Here's another solution using Plack (may be found on CPAN):
<
my $app = sub {
return [ 200,
Line 1,396 ⟶ 1,501:
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:
<
Use <
=={{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.
<!--<
<span style="color: #000080;font-style:italic;">-- demo\rosetta\SimpleHttpServer.exw</span>
<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>
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Line 1,429 ⟶ 1,535:
</html>
<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>
Line 1,449 ⟶ 1,555:
<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>
<!--</
{{Out}}
Server console, once you have opened http://localhost:8080 in your browser, or run curl http://localhost:8080
Line 1,469 ⟶ 1,575:
=={{header|PHP}}==
<
// AF_INET6 for IPv6 // IP
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
Line 1,488 ⟶ 1,594:
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?></
=={{header|PicoLisp}}==
Contents of the file "goodbye.l":
<
"Goodbye, World!" )</
Start server:
<pre>$ pil @lib/http.l @lib/xhtml.l -'server 8080 "goodbye.l"' -wait</pre>
Line 1,499 ⟶ 1,605:
=={{header|Pike}}==
<syntaxhighlight lang="pike">
void handle_request(Protocols.HTTP.Server.Request request)
{
Line 1,511 ⟶ 1,617:
return -1; // -1 is a special case that retirns control to the backend
}
</syntaxhighlight>
=={{header|Pony}}==
Using only in-built TCP listeners, not the HTTP server package
<syntaxhighlight lang="pony">
use "net"
Line 1,565 ⟶ 1,671:
// 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,571 ⟶ 1,677:
{{works with|YAP}}
<
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
Line 1,588 ⟶ 1,694:
% wrapped in <h1></h1> tags, "Goodbye, World!".
say_goodbye(_Request) :- reply_html_page([title('Howdy')],
[h1('Goodbye, World!')]).</
=={{header|PureBasic}}==
<
MessageRequester("Error", "Can't initialize the network !")
End
Line 1,613 ⟶ 1,719:
Else
MessageRequester("Error", "Can't create the server (port in use ?).")
EndIf</
=={{header|Python}}==
Using the <code>wsgiref.simple_server</code> module (Python < 3.2).
<
def app(environ, start_response):
Line 1,625 ⟶ 1,731:
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()</
Using the <code>http.server</code> module (Python 3).
<
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Line 1,664 ⟶ 1,770:
except KeyboardInterrupt:
pass
</syntaxhighlight>
=={{header|R}}==
<
library(httpuv)
Line 1,679 ⟶ 1,785:
</syntaxhighlight>
=={{header|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>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo}}
<syntaxhighlight lang="raku"
loop {
my $conn = $listen.accept;
Line 1,699 ⟶ 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;
}</
Async:
<syntaxhighlight lang="raku"
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply.lines -> $line {
Line 1,708 ⟶ 1,814:
}
}
}</
=={{header|REALbasic}}==
<syntaxhighlight lang="vb">
Class HTTPSock
Inherits TCPSocket
Line 1,745 ⟶ 1,851:
End Sub
End Class
</syntaxhighlight>
=={{header|REXX}}==
Based on the UNIX Shell entry. Works with Regina, tested on GNU/Linux. Requires netcat as nc.
<
response.1 = 'HTTP/1.1 200 OK' || '0D0A'X,
|| 'Connection: close' || '0D0A'X,
Line 1,761 ⟶ 1,867:
DO FOREVER
ADDRESS SYSTEM 'nc -l 8080' WITH INPUT STEM response.
END</
=={{header|Ring}}==
<
Load "guilib.ring"
Line 1,822 ⟶ 1,928:
close()
}
</syntaxhighlight>
=={{header|Ruby}}==
Using the WEBrick module from Ruby's standard library.
<
server = WEBrick::HTTPServer.new(:Port => 8080)
server.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
trap("INT") {server.shutdown}
server.start</
Same code without <code>trap</code>, in a single statement using <code>tap</code>.
<
WEBrick::HTTPServer.new(:Port => 80).tap {|srv|
srv.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
}.start</
Using the [http://www.sinatrarb.com/ sinatra] gem:
<
get("/") { "Goodbye, World!" }</
=={{header|Run BASIC}}==
<
=={{header|Rust}}==
Basically no error handling. This web server will simply panic if there is any sort of error.
<
use std::thread;
use std::io::Write;
Line 1,874 ⟶ 1,980:
}
}
</syntaxhighlight>
=={{header|Rye}}==
<syntaxhighlight lang="clojure">rye .needs { http }
new-server ":8080"
|handle "/" fn { r w } { write w "Goodbye, World!" }
|serve</syntaxhighlight>
=={{header|Salmon}}==
<
/* Don't do any logging. */
Line 1,883 ⟶ 1,996:
simple_http_server(8080, procedure(header, connection)
{ respond_text(connection, "Goodbye, World!"); });</
=={{header|Scala}}==
{{libheader|Scala}}
{{Trans|Java}}It shows that Scala can simply embed XML fragments.
<
import java.net.ServerSocket
Line 1,911 ⟶ 2,024:
sock.close()
}
}</
=={{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].
<
include "listener.s7i";
Line 1,934 ⟶ 2,047:
close(sock);
end while;
end func;</
=={{header|Sidef}}==
Using the low-level ''Socket'' object:
<
var protocol = Socket.getprotobyname("tcp");
Line 1,962 ⟶ 2,075:
"<body>Goodbye, world!</body></html>\r\n");
client.close;
}</
A more friendly interface, using the ''IO::Socket::INET'' library:
<
var sock = inet.new( LocalAddr => "127.0.0.1:8080",
Line 1,978 ⟶ 2,091:
"<body>Goodbye, world!</body></html>\r\n");
client.close;
}</
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
starting server:
<
|myServer service|
Line 1,996 ⟶ 2,109:
service linkNames:#('/' ).
service registerServiceOn: myServer.
myServer start.</
Be aware that the above is an ad-hoc minimal scripting example.
Normally, a service subclass is used and
Line 2,008 ⟶ 2,121:
that includes a ZnServer class.
Here's the simplest solution to start a web server:
<
onRequestRespond: [ :request |
ZnResponse ok: (ZnEntity text: 'Hello World!') ].</
To stop the server, use the following:
<syntaxhighlight lang
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world!" ) ;
Line 2,044 ⟶ 2,157:
end handle x => (Socket.close listener; raise x)
;
</syntaxhighlight>
call - smlnj interpreter
- serve (INetSock.TCP.socket()) 8080 ;
Line 2,062 ⟶ 2,175:
===Tcl 8.x===
This version is adapted from [http://wiki.tcl.tk/28414 the Tcler's Wiki].
<
while {[gets $chan] ne ""} {}
puts $chan "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n"
Line 2,069 ⟶ 2,182:
}
socket -server accept 8080
vwait forever</
===Jim Tcl===
Jim is a small footprint reimplementation of Tcl with modern features.
<
$s readable {
set client [$s accept]
Line 2,080 ⟶ 2,193:
$client close
}
vwait done</
=={{header|UNIX Shell}}==
<
=={{header|Wart}}==
<
accepting client :from socket
making stdout outfile+fd.client
Line 2,094 ⟶ 2,207:
prn "Content-type: text/plain"
prn ""
prn "Hello, world!"</
=={{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
<
const SERVLET_THREADS=4;
Line 2,143 ⟶ 2,486:
println("HTTP server started at http://",
serverSocket.hostname, ":", serverSocket.port);
serverSocket.listen(jobPipe);</
|