Hello world/Web server: Difference between revisions

Content added Content deleted
(→‎{{header|Frink}}: Fixed to send HTTP headers)
m (syntax highlighting fixup automation)
Line 29: Line 29:
{{libheader|AWS}}
{{libheader|AWS}}
Uses many defaults, such as 5 max simultaneous connections.
Uses many defaults, such as 5 max simultaneous connections.
<lang ada>
<syntaxhighlight lang="ada">
with AWS; use AWS;
with AWS; use AWS;
with AWS.Response;
with AWS.Response;
Line 49: Line 49:
Server.Shutdown (TheServer);
Server.Shutdown (TheServer);
end HelloHTTP;
end HelloHTTP;
</syntaxhighlight>
</lang>


=={{header|Aime}}==
=={{header|Aime}}==
Goodbye, world! with random colors and socket polling:
Goodbye, world! with random colors and socket polling:
<lang aime>void
<syntaxhighlight lang="aime">void
serve(dispatch w, file s, list colors)
serve(dispatch w, file s, list colors)
{
{
Line 86: Line 86:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Or simply:
Or simply:
<lang aime>file i, o, s;
<syntaxhighlight lang="aime">file i, o, s;


tcpip_listen(s, 8080, 0);
tcpip_listen(s, 8080, 0);
Line 98: Line 98:
"<body><h1>Goodbye, world!</h1></body></html>\n");
"<body><h1>Goodbye, world!</h1></body></html>\n");
f_flush(o);
f_flush(o);
}</lang>
}</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
VERSION 1: "Hopper" flavour:
VERSION 1: "Hopper" flavour:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
// Hello world! mode Server
// Hello world! mode Server


Line 129: Line 129:
exit(0)
exit(0)
</syntaxhighlight>
</lang>
VERSION 2: "Hopper-BASIC" flavour
VERSION 2: "Hopper-BASIC" flavour
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
// Hello world! mode Server: desde el navegador, escriba localhost:8080
// Hello world! mode Server: desde el navegador, escriba localhost:8080


Line 164: Line 164:
CloseSocket(fd)
CloseSocket(fd)
End
End
</syntaxhighlight>
</lang>
{{out}}
{{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>Open your browser, and type in the navigation bar: "localhost: 8080": It will show "Goodbye World!" in huge letters and adorable lovecraftian colors!
Line 171: Line 171:
=={{header|AntLang}}==
=={{header|AntLang}}==
In plain AntLang:
In plain AntLang:
<lang AntLang>serv: httprun[8080; {"HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nGoodbye, World!"}]</lang>
<syntaxhighlight lang="antlang">serv: httprun[8080; {"HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nGoodbye, World!"}]</syntaxhighlight>


Using ALC:
Using ALC:
<lang AntLang>load["handlers.ant"]
<syntaxhighlight lang="antlang">load["handlers.ant"]
serv: httprun[8080; {httpwrap["Goodbye, World!"]}]</lang>
serv: httprun[8080; {httpwrap["Goodbye, World!"]}]</syntaxhighlight>


To close the server:
To close the server:
<lang AntLang>kill[serv]</lang>
<syntaxhighlight lang="antlang">kill[serv]</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>serve.port:8080 [ GET "/" -> "Goodbye, World!" ]</lang>
<syntaxhighlight lang="rebol">serve.port:8080 [ GET "/" -> "Goodbye, World!" ]</syntaxhighlight>


{{out}}
{{out}}
Line 191: Line 191:


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
TCPStartup()
TCPStartup()
$socket = TCPListen("0.0.0.0",8080)
$socket = TCPListen("0.0.0.0",8080)
Line 209: Line 209:
TCPCloseSocket($newConnection)
TCPCloseSocket($newConnection)
WEnd
WEnd
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
Line 216: Line 216:
[http://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html#Primitive-Service]
[http://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html#Primitive-Service]
(Documentation is licensed under GNU Free Documentation License, Version 1.3)
(Documentation is licensed under GNU Free Documentation License, Version 1.3)
<lang AWK>#!/usr/bin/gawk -f
<syntaxhighlight lang="awk">#!/usr/bin/gawk -f
BEGIN {
BEGIN {
RS = ORS = "\r\n"
RS = ORS = "\r\n"
Line 230: Line 230:
continue;
continue;
close(HttpService)
close(HttpService)
}</lang>
}</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
Requires BaCon 4.2 or higher.
Requires BaCon 4.2 or higher.
<lang bacon>' Define HTTP constants
<syntaxhighlight lang="bacon">' Define HTTP constants
CONST New$ = CHR$(13) & NL$
CONST New$ = CHR$(13) & NL$
CONST Sep$ = CHR$(13) & NL$ & CHR$(13) & NL$
CONST Sep$ = CHR$(13) & NL$ & CHR$(13) & NL$
Line 276: Line 276:
ENDFORK
ENDFORK
ENDIF
ENDIF
WEND</lang>
WEND</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
This explicitly supports multiple concurrent connections.
This explicitly supports multiple concurrent connections.
<lang bbcbasic> INSTALL @lib$+"SOCKLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SOCKLIB"
PROC_initsockets
PROC_initsockets
Line 342: Line 342:
WAIT 0
WAIT 0
UNTIL FALSE
UNTIL FALSE
END</lang>
END</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
This is, um, slightly longer than what other languages would be.
This is, um, slightly longer than what other languages would be.
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
Line 399: Line 399:
close(client_fd);
close(client_fd);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang CSharp>using System.Text;
<syntaxhighlight lang="csharp">using System.Text;
using System.Net.Sockets;
using System.Net.Sockets;
using System.Net;
using System.Net;
Line 428: Line 428:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{works with|NancyFX}}<lang CSharp>namespace Webserver
{{works with|NancyFX}}<syntaxhighlight lang="csharp">namespace Webserver
{
{
using System;
using System;
Line 454: Line 454:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 465: Line 465:


File: src/goodbye_world/handler.clj
File: src/goodbye_world/handler.clj
<lang clojure>(ns goodbye-world.handler
<syntaxhighlight lang="clojure">(ns goodbye-world.handler
(:require [compojure.core :refer :all]
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[compojure.handler :as handler]
Line 476: Line 476:


(def app
(def app
(handler/site app-routes))</lang>
(handler/site app-routes))</syntaxhighlight>


To start up the server on port 8080, run the following from the project's root:
To start up the server on port 8080, run the following from the project's root:
Line 486: Line 486:
Here's the example with a pre-built server:
Here's the example with a pre-built server:


<lang lisp>(ql:quickload :hunchentoot)
<syntaxhighlight lang="lisp">(ql:quickload :hunchentoot)
(defpackage :hello-web (:use :cl :hunchentoot))
(defpackage :hello-web (:use :cl :hunchentoot))
(in-package :hello-web)
(in-package :hello-web)
Line 492: Line 492:
(define-easy-handler (hello :uri "/") () "Goodbye, World!")
(define-easy-handler (hello :uri "/") () "Goodbye, World!")


(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080)))</lang>
(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080)))</syntaxhighlight>


----
----
Line 498: Line 498:
Here's an example of doing everything manually
Here's an example of doing everything manually


<lang lisp>(ql:quickload :usocket)
<syntaxhighlight lang="lisp">(ql:quickload :usocket)
(defpackage :hello-web-manual (:use :cl :usocket))
(defpackage :hello-web-manual (:use :cl :usocket))
(in-package :hello-web-manual)
(in-package :hello-web-manual)
Line 535: Line 535:
(loop for c in connections do (loop while (socket-close c))))))
(loop for c in connections do (loop while (socket-close c))))))


(serve 8080)</lang>
(serve 8080)</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==


<lang crystal>
<syntaxhighlight lang="crystal">
require "http/server"
require "http/server"


Line 547: Line 547:


server.listen(8080)
server.listen(8080)
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
Line 553: Line 553:
''If you copy from this page, be careful with extraneous spaces on the empty lines in the heredoc''.
''If you copy from this page, be careful with extraneous spaces on the empty lines in the heredoc''.


<lang D>import std.socket, std.array;
<syntaxhighlight lang="d">import std.socket, std.array;


ushort port = 8080;
ushort port = 8080;
Line 577: Line 577:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Dart}}==
=={{header|Dart}}==
<lang d>import 'dart:io';
<syntaxhighlight lang="d">import 'dart:io';


main() async {
main() async {
Line 590: Line 590:
..close();
..close();
}
}
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program HelloWorldWebServer;
<syntaxhighlight lang="delphi">program HelloWorldWebServer;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 642: Line 642:
lWebServer.Free;
lWebServer.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Dylan.NET|Dylan.NET}}==
=={{header|Dylan.NET|Dylan.NET}}==
<syntaxhighlight lang="dylan.net">
<lang Dylan.NET>
//compile with dylan.NET 11.5.1.2 or later!!
//compile with dylan.NET 11.5.1.2 or later!!
#refstdasm "mscorlib.dll"
#refstdasm "mscorlib.dll"
Line 682: Line 682:


end namespace
end namespace
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 689: Line 689:
I fail to see how a longer time will serve any purpose.
I fail to see how a longer time will serve any purpose.


<syntaxhighlight lang="erlang">
<lang Erlang>
-module( hello_world_web_server ).
-module( hello_world_web_server ).


Line 711: Line 711:
timer:sleep( 30000 ),
timer:sleep( 30000 ),
httpd_stop( Pid ).
httpd_stop( Pid ).
</syntaxhighlight>
</lang>


=={{header|Fantom}}==
=={{header|Fantom}}==
<lang fantom>using web
<syntaxhighlight lang="fantom">using web
using wisp
using wisp


Line 738: Line 738:
while (true) {} // stay running
while (true) {} // stay running
}
}
}</lang>
}</syntaxhighlight>


=={{header|Fortran}}==
=={{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:
There is no network library in fortran. Use C interoperability and some C compatible library or just start node.js simple web server:
<lang fortran>
<syntaxhighlight lang="fortran">
program http_example
program http_example
implicit none
implicit none
Line 757: Line 757:


end program http_example
end program http_example
</syntaxhighlight>
</lang>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
<lang pascal>program HelloWorldServer;
<syntaxhighlight lang="pascal">program HelloWorldServer;
{$mode objfpc}{$H+}
{$mode objfpc}{$H+}
uses
uses
Line 801: Line 801:
Serv.Free;
Serv.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>




=={{header|Frink}}==
=={{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.
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.
<lang frink>ss = newJava["java.net.ServerSocket", 8080]
<syntaxhighlight lang="frink">ss = newJava["java.net.ServerSocket", 8080]
while true
while true
{
{
Line 815: Line 815:
w.println["Goodbye, World!"]
w.println["Goodbye, World!"]
w.close[]
w.close[]
}</lang>
}</syntaxhighlight>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>native java.io.PrintWriter
<syntaxhighlight lang="funl">native java.io.PrintWriter
native java.net.ServerSocket
native java.net.ServerSocket


Line 830: Line 830:
PrintWriter( socket.getOutputStream(), true ).println( 'hello world' )
PrintWriter( socket.getOutputStream(), true ).println( 'hello world' )
socket.shutdownOutput()
socket.shutdownOutput()
socket.close()</lang>
socket.close()</syntaxhighlight>


=={{header|Gastona}}==
=={{header|Gastona}}==
Line 836: Line 836:
following the server activity and also being able to quit it by closing the window.
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.
But it is not stritctly needed, just the unit #listix# would do the job.
<lang gastona>#javaj#
<syntaxhighlight lang="gastona">#javaj#


<frames> oConsole
<frames> oConsole
Line 849: Line 849:
// Goodbye world!
// Goodbye world!
//</body></html>
//</body></html>
</syntaxhighlight>
</lang>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>/**
<syntaxhighlight lang="genie">/**
* Based on https://wiki.gnome.org/Projects/Genie/GIONetworkingSample
* Based on https://wiki.gnome.org/Projects/Genie/GIONetworkingSample
* Based on an example of Jezra Lickter http://hoof.jezra.net/snip/nV
* Based on an example of Jezra Lickter http://hoof.jezra.net/snip/nV
Line 927: Line 927:
dos.put_string(response.data)
dos.put_string(response.data)
except e : Error
except e : Error
stderr.printf("%s\n", e.message)</lang>
stderr.printf("%s\n", e.message)</syntaxhighlight>


{{out}}
{{out}}
Line 938: Line 938:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 952: Line 952:
log.Fatal(http.ListenAndServe(":8080", nil))
log.Fatal(http.ListenAndServe(":8080", nil))
}
}
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 959: Line 959:
using the [http://www.yesodweb.com/book/conduits conduit] stack:
using the [http://www.yesodweb.com/book/conduits conduit] stack:


<lang haskell>{-# LANGUAGE OverloadedStrings #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}


import Data.ByteString.Char8 ()
import Data.ByteString.Char8 ()
Line 967: Line 967:
main :: IO ()
main :: IO ()
main = runTCPServer (ServerSettings 8080 "127.0.0.1") $ const (yield response $$)
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"</lang>
where response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"</syntaxhighlight>


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]):
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]):


<lang haskell>{-# LANGUAGE OverloadedStrings #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}


import Data.ByteString.Char8 ()
import Data.ByteString.Char8 ()
Line 985: Line 985:
loop s = forever $ forkIO . request . fst =<< accept s
loop s = forever $ forkIO . request . fst =<< accept s
request c = sendAll c response `finally` sClose c
request c = sendAll c response `finally` sClose c
response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"</lang>
response = "HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"</syntaxhighlight>


Both works like this:
Both works like this:
Line 999: Line 999:
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]):
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]):


<lang haskell>{-# LANGUAGE OverloadedStrings #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.Wai
Line 1,018: Line 1,018:
index x = responseBuilder status200 [("Content-Type", "text/plain")] $ mconcat $ map copyByteString
index x = responseBuilder status200 [("Content-Type", "text/plain")] $ mconcat $ map copyByteString
[ "Hello World!\n" ]</lang>
[ "Hello World!\n" ]</syntaxhighlight>


Work like this:
Work like this:
Line 1,043: Line 1,043:
=={{header|Io}}==
=={{header|Io}}==


<syntaxhighlight lang="io">
<lang io>
WebRequest := Object clone do(
WebRequest := Object clone do(
handleSocket := method(aSocket,
handleSocket := method(aSocket,
Line 1,059: Line 1,059:


WebServer start
WebServer start
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
Line 1,065: Line 1,065:
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,
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:
start jhs, visit http://127.0.0.1:8080/jijx then enter the text:
<lang j>'Goodbye, World!'</lang>
<syntaxhighlight lang="j">'Goodbye, World!'</syntaxhighlight>
This will compute the desired result and display it (actually, it will be displayed twice since the original string will also be displayed).
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)...
This would be even simpler if you could just use the default jhs port (65001)...
Line 1,075: Line 1,075:
For example, here is a web server which ignores the client's request
For example, here is a web server which ignores the client's request
and always returns Goodbye, World:
and always returns Goodbye, World:
<lang j>hello=: verb define
<syntaxhighlight lang="j">hello=: verb define
8080 hello y NB. try to use port 8080 by default
8080 hello y NB. try to use port 8080 by default
:
:
Line 1,101: Line 1,101:
responseFor=: dyad define
responseFor=: dyad define
'HTTP/1.0 200 OK',CRLF,'Content-Type: text/plain',CRLF,CRLF,'Goodbye, World!',CRLF
'HTTP/1.0 200 OK',CRLF,'Content-Type: text/plain',CRLF,CRLF,'Goodbye, World!',CRLF
)</lang>
)</syntaxhighlight>
To deploy this server, once it has been defined, run
To deploy this server, once it has been defined, run
<lang j>hello''</lang>
<syntaxhighlight lang="j">hello''</syntaxhighlight>
This version works because reasonable http requests fit in a single tcp packet.
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.)
(And note that the server waits for one tcp packet before responding.)
Line 1,111: Line 1,111:
Multiple requests will be served in the order that they reach the server,
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).
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).
<lang java>import java.io.IOException;
<syntaxhighlight lang="java">import java.io.IOException;
import java.io.PrintWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.ServerSocket;
Line 1,126: Line 1,126:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,132: Line 1,132:
{{works with|Node.js}}
{{works with|Node.js}}


<lang javascript>var http = require('http');
<syntaxhighlight lang="javascript">var http = require('http');


http.createServer(function (req, res) {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Goodbye, World!\n');
res.end('Goodbye, World!\n');
}).listen(8080, '127.0.0.1');</lang>
}).listen(8080, '127.0.0.1');</syntaxhighlight>


It scales:
It scales:
Line 1,169: Line 1,169:
=={{header|Julia}}==
=={{header|Julia}}==
Requires the HttpServer package to have previously been installed with 'Pkg.add("HttpServer")'
Requires the HttpServer package to have previously been installed with 'Pkg.add("HttpServer")'
<lang Julia>using HttpServer
<syntaxhighlight lang="julia">using HttpServer
server = Server() do req, res
server = Server() do req, res
"Goodbye, World!"
"Goodbye, World!"
end
end
run(server, 8080)
run(server, 8080)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>import java.io.PrintWriter
<syntaxhighlight lang="scala">import java.io.PrintWriter
import java.net.ServerSocket
import java.net.ServerSocket


Line 1,188: Line 1,188:
sock.close()
sock.close()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
Line 1,194: Line 1,194:
here's how you can create a basic multi-threaded webserver
here's how you can create a basic multi-threaded webserver
of your own to complete this request:
of your own to complete this request:
<lang lasso>local(server) = net_tcp
<syntaxhighlight lang="lasso">local(server) = net_tcp
handle => { #server->close }
handle => { #server->close }
#server->bind(8080) & listen & forEachAccept => {
#server->bind(8080) & listen & forEachAccept => {
Line 1,213: Line 1,213:
#con->writeBytes(bytes(#response))
#con->writeBytes(bytes(#response))
}
}
}</lang>
}</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Line 1,219: Line 1,219:
but it's close relative ''Run BASIC'' is designed for serving webpages easily.
but it's close relative ''Run BASIC'' is designed for serving webpages easily.
The task becomes simply ..
The task becomes simply ..
<lang lb>print "hello world!" </lang>
<syntaxhighlight lang="lb">print "hello world!" </syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
{{works with|lua|5.2.4}}
{{works with|lua|5.2.4}}
{{libheader|LuaSocket}}
{{libheader|LuaSocket}}
<lang lua>local socket = require "socket"
<syntaxhighlight lang="lua">local socket = require "socket"
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 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!"
local content = "<!doctype html><html><title>Goodbye, World!</title><h1>Goodbye, World!"
Line 1,233: Line 1,233:
client:close()
client:close()
until not client or not ok
until not client or not ok
server:close()</lang>
server:close()</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>listener =
<syntaxhighlight lang="mathematica">listener =
SocketListen["127.0.0.1:8080",
SocketListen["127.0.0.1:8080",
Function[{assoc},
Function[{assoc},
Line 1,243: Line 1,243:
"HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"];
"HTTP/1.0 200 OK\nContent-Length: 16\n\nGoodbye, World!\n"];
Close[client]]]]
Close[client]]]]
SystemOpen["http://127.0.0.1:8080"]</lang>
SystemOpen["http://127.0.0.1:8080"]</syntaxhighlight>
Clean up:
Clean up:
<lang Mathematica>DeleteObject[listener];
<syntaxhighlight lang="mathematica">DeleteObject[listener];
Close[listener["Socket"]]</lang>
Close[listener["Socket"]]</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
This is a CGI executable:
This is a CGI executable:
<lang>
<syntaxhighlight lang="text">
MODULE access;
MODULE access;


Line 1,262: Line 1,262:
WriteLn
WriteLn
END access.
END access.
</syntaxhighlight>
</lang>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{Trans|Java}}
{{Trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,303: Line 1,303:
end listener
end listener
return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import asynchttpserver, asyncdispatch
<syntaxhighlight lang="nim">import asynchttpserver, asyncdispatch


proc cb(req: Request) {.async.} =
proc cb(req: Request) {.async.} =
Line 1,313: Line 1,313:
asyncCheck newAsyncHttpServer().serve(Port(8080), cb)
asyncCheck newAsyncHttpServer().serve(Port(8080), cb)
runForever()
runForever()
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use Net;
use Net;
use Concurrency;
use Concurrency;
Line 1,335: Line 1,335:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
This code is derived from this [http://ocamlunix.forge.ocamlcore.org/sockets.html#htoc54 ocaml-unix documentation].
This code is derived from this [http://ocamlunix.forge.ocamlcore.org/sockets.html#htoc54 ocaml-unix documentation].
<lang ocaml>let try_finalise f x finally y =
<syntaxhighlight lang="ocaml">let try_finalise f x finally y =
let res = try f x with e -> finally y; raise e in
let res = try f x with e -> finally y; raise e in
finally y;
finally y;
Line 1,395: Line 1,395:


let _ =
let _ =
Unix.handle_unix_error server ()</lang>
Unix.handle_unix_error server ()</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
This sample sends 200 OK on any request and echoes the request headers.
This sample sends 200 OK on any request and echoes the request headers.
<lang ol>(import (lib http))
<syntaxhighlight lang="ol">(import (lib http))


(http:run 8080 (lambda (fd request headers send close)
(http:run 8080 (lambda (fd request headers send close)
Line 1,413: Line 1,413:
(close #t)
(close #t)
))
))
</syntaxhighlight>
</lang>


=={{header|Opa}}==
=={{header|Opa}}==
From [http://doc.opalang.org/index.html#_a_first_peek_at_opa Opa documentation]:
From [http://doc.opalang.org/index.html#_a_first_peek_at_opa Opa documentation]:
<lang ocaml>server = one_page_server("Hello", -> <>Goodbye, world</>)</lang>
<syntaxhighlight lang="ocaml">server = one_page_server("Hello", -> <>Goodbye, world</>)</syntaxhighlight>
Compile and run:
Compile and run:
<lang bash>opa file.opa --</lang>
<syntaxhighlight lang="bash">opa file.opa --</syntaxhighlight>


=={{header|Panda}}==
=={{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.
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.


<lang panda>8080.port.listen.say("Hello world!")</lang>
<syntaxhighlight lang="panda">8080.port.listen.say("Hello world!")</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>use Socket;
<syntaxhighlight lang="perl">use Socket;


my $port = 8080;
my $port = 8080;
Line 1,451: Line 1,451:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close CLIENT;
close CLIENT;
}</lang>
}</syntaxhighlight>
Various modules exist for using sockets, including the popular IO::Socket
Various modules exist for using sockets, including the popular IO::Socket
which provides a simpler and more friendly OO interface for the socket layer.
which provides a simpler and more friendly OO interface for the socket layer.
Here is the solution using this module:
Here is the solution using this module:
{{libheader|IO::Socket::INET}}
{{libheader|IO::Socket::INET}}
<lang Perl>use IO::Socket::INET;
<syntaxhighlight lang="perl">use IO::Socket::INET;


my $sock = new IO::Socket::INET ( LocalAddr => "127.0.0.1:8080",
my $sock = new IO::Socket::INET ( LocalAddr => "127.0.0.1:8080",
Line 1,467: Line 1,467:
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
"<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>\r\n";
close $client;
close $client;
}</lang>
}</syntaxhighlight>


Using Perl's glue power, provide a suicide note
Using Perl's glue power, provide a suicide note
with visitor counter via netcat:
with visitor counter via netcat:
<lang Perl>while (++(our $vn)) {
<syntaxhighlight lang="perl">while (++(our $vn)) {
open NC, "|-", qw(nc -l -p 8080 -q 1);
open NC, "|-", qw(nc -l -p 8080 -q 1);
print NC "HTTP/1.0 200 OK\xd\xa",
print NC "HTTP/1.0 200 OK\xd\xa",
"Content-type: text/plain; charset=utf-8\xd\xa\xd\xa",
"Content-type: text/plain; charset=utf-8\xd\xa\xd\xa",
"Goodbye, World! (hello, visitor No. $vn!)\xd\xa";
"Goodbye, World! (hello, visitor No. $vn!)\xd\xa";
}</lang>
}</syntaxhighlight>


Here's another solution using Plack (may be found on CPAN):
Here's another solution using Plack (may be found on CPAN):
<lang Perl>use Plack::Runner;
<syntaxhighlight lang="perl">use Plack::Runner;
my $app = sub {
my $app = sub {
return [ 200,
return [ 200,
Line 1,488: Line 1,488:
my $runner = Plack::Runner->new;
my $runner = Plack::Runner->new;
$runner->parse_options('--host' => 'localhost', '--port' => 8080);
$runner->parse_options('--host' => 'localhost', '--port' => 8080);
$runner->run($app);</lang>
$runner->run($app);</syntaxhighlight>


When using plackup, then this may be compressed to one line:
When using plackup, then this may be compressed to one line:
<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>' ] ] };</lang>
<syntaxhighlight 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>' ] ] };</syntaxhighlight>
Use <lang Shell>plackup --host localhost --port 8080 script.psgi</lang> to start the webserver.
Use <syntaxhighlight lang="shell">plackup --host localhost --port 8080 script.psgi</syntaxhighlight> to start the webserver.


=={{header|Phix}}==
=={{header|Phix}}==
Windows only for now (should be relatively straightforward to get it working on linux)<br>
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.
Output as C, code is however a translation of a FASM example.
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\SimpleHttpServer.exw</span>
<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;">without</span> <span style="color: #008080;">js</span>
Line 1,547: Line 1,547:
<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: #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>
<span style="color: #7060A8;">WSACleanup</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{Out}}
{{Out}}
Server console, once you have opened http://localhost:8080 in your browser, or run curl http://localhost:8080
Server console, once you have opened http://localhost:8080 in your browser, or run curl http://localhost:8080
Line 1,562: Line 1,562:


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP><?php
<syntaxhighlight lang="php"><?php
// AF_INET6 for IPv6 // IP
// AF_INET6 for IPv6 // IP
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
Line 1,581: Line 1,581:
else usleep(100000); // limits CPU usage by sleeping after doing every request
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
}
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Contents of the file "goodbye.l":
Contents of the file "goodbye.l":
<lang PicoLisp>(html 0 "Bye" NIL NIL
<syntaxhighlight lang="picolisp">(html 0 "Bye" NIL NIL
"Goodbye, World!" )</lang>
"Goodbye, World!" )</syntaxhighlight>
Start server:
Start server:
<pre>$ pil @lib/http.l @lib/xhtml.l -'server 8080 "goodbye.l"' -wait</pre>
<pre>$ pil @lib/http.l @lib/xhtml.l -'server 8080 "goodbye.l"' -wait</pre>
Line 1,592: Line 1,592:
=={{header|Pike}}==
=={{header|Pike}}==


<syntaxhighlight lang="pike">
<lang Pike>
void handle_request(Protocols.HTTP.Server.Request request)
void handle_request(Protocols.HTTP.Server.Request request)
{
{
Line 1,604: Line 1,604:
return -1; // -1 is a special case that retirns control to the backend
return -1; // -1 is a special case that retirns control to the backend
}
}
</syntaxhighlight>
</lang>


=={{header|Pony}}==
=={{header|Pony}}==
Using only in-built TCP listeners, not the HTTP server package
Using only in-built TCP listeners, not the HTTP server package
<syntaxhighlight lang="pony">
<lang Pony>
use "net"
use "net"


Line 1,658: Line 1,658:
// Impl for when client fails to connect to all possible addresses for the server
// Impl for when client fails to connect to all possible addresses for the server
fun ref connect_failed(_: TCPConnection ref) => None
fun ref connect_failed(_: TCPConnection ref) => None
</syntaxhighlight>
</lang>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 1,664: Line 1,664:
{{works with|YAP}}
{{works with|YAP}}


<lang Prolog>% The following modules are used in the main module to start a server.
<syntaxhighlight lang="prolog">% The following modules are used in the main module to start a server.
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_dispatch)).
Line 1,681: Line 1,681:
% wrapped in <h1></h1> tags, "Goodbye, World!".
% wrapped in <h1></h1> tags, "Goodbye, World!".
say_goodbye(_Request) :- reply_html_page([title('Howdy')],
say_goodbye(_Request) :- reply_html_page([title('Howdy')],
[h1('Goodbye, World!')]).</lang>
[h1('Goodbye, World!')]).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If InitNetwork() = 0
<syntaxhighlight lang="purebasic">If InitNetwork() = 0
MessageRequester("Error", "Can't initialize the network !")
MessageRequester("Error", "Can't initialize the network !")
End
End
Line 1,706: Line 1,706:
Else
Else
MessageRequester("Error", "Can't create the server (port in use ?).")
MessageRequester("Error", "Can't create the server (port in use ?).")
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Using the <code>wsgiref.simple_server</code> module (Python < 3.2).
Using the <code>wsgiref.simple_server</code> module (Python < 3.2).


<lang Python>from wsgiref.simple_server import make_server
<syntaxhighlight lang="python">from wsgiref.simple_server import make_server


def app(environ, start_response):
def app(environ, start_response):
Line 1,718: Line 1,718:


server = make_server('127.0.0.1', 8080, app)
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()</lang>
server.serve_forever()</syntaxhighlight>


Using the <code>http.server</code> module (Python 3).
Using the <code>http.server</code> module (Python 3).


<lang Python>import threading
<syntaxhighlight lang="python">import threading


from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Line 1,757: Line 1,757:
except KeyboardInterrupt:
except KeyboardInterrupt:
pass
pass
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
<lang rsplus>
<syntaxhighlight lang="rsplus">
library(httpuv)
library(httpuv)


Line 1,772: Line 1,772:




</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require web-server/servlet web-server/servlet-env)
(require web-server/servlet web-server/servlet-env)
(define (start req) (response/xexpr "Goodbye, World!"))
(define (start req) (response/xexpr "Goodbye, World!"))
(serve/servlet start #:port 8080 #:servlet-path "/")
(serve/servlet start #:port 8080 #:servlet-path "/")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo}}
{{works with|Rakudo}}
<lang perl6>my $listen = IO::Socket::INET.new(:listen, :localhost<localhost>, :localport(8080));
<syntaxhighlight lang="raku" line>my $listen = IO::Socket::INET.new(:listen, :localhost<localhost>, :localport(8080));
loop {
loop {
my $conn = $listen.accept;
my $conn = $listen.accept;
Line 1,792: Line 1,792:
$conn.print: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n";
$conn.print: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n";
$conn.close;
$conn.close;
}</lang>
}</syntaxhighlight>
Async:
Async:
<lang perl6>react {
<syntaxhighlight lang="raku" line>react {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn {
whenever $conn.Supply.lines -> $line {
whenever $conn.Supply.lines -> $line {
Line 1,801: Line 1,801:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|REALbasic}}==
=={{header|REALbasic}}==


<syntaxhighlight lang="vb">
<lang vb>
Class HTTPSock
Class HTTPSock
Inherits TCPSocket
Inherits TCPSocket
Line 1,838: Line 1,838:
End Sub
End Sub
End Class
End Class
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Based on the UNIX Shell entry. Works with Regina, tested on GNU/Linux. Requires netcat as nc.
Based on the UNIX Shell entry. Works with Regina, tested on GNU/Linux. Requires netcat as nc.


<lang rexx>/* HTTP hello server */
<syntaxhighlight lang="rexx">/* HTTP hello server */
response.1 = 'HTTP/1.1 200 OK' || '0D0A'X,
response.1 = 'HTTP/1.1 200 OK' || '0D0A'X,
|| 'Connection: close' || '0D0A'X,
|| 'Connection: close' || '0D0A'X,
Line 1,854: Line 1,854:
DO FOREVER
DO FOREVER
ADDRESS SYSTEM 'nc -l 8080' WITH INPUT STEM response.
ADDRESS SYSTEM 'nc -l 8080' WITH INPUT STEM response.
END</lang>
END</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
Load "guilib.ring"
Load "guilib.ring"


Line 1,915: Line 1,915:
close()
close()
}
}
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Using the WEBrick module from Ruby's standard library.
Using the WEBrick module from Ruby's standard library.
<lang ruby>require 'webrick'
<syntaxhighlight lang="ruby">require 'webrick'
server = WEBrick::HTTPServer.new(:Port => 8080)
server = WEBrick::HTTPServer.new(:Port => 8080)
server.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
server.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
trap("INT") {server.shutdown}
trap("INT") {server.shutdown}
server.start</lang>
server.start</syntaxhighlight>


Same code without <code>trap</code>, in a single statement using <code>tap</code>.
Same code without <code>trap</code>, in a single statement using <code>tap</code>.
<lang Ruby>require 'webrick'
<syntaxhighlight lang="ruby">require 'webrick'
WEBrick::HTTPServer.new(:Port => 80).tap {|srv|
WEBrick::HTTPServer.new(:Port => 80).tap {|srv|
srv.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
srv.mount_proc('/') {|request, response| response.body = "Goodbye, World!"}
}.start</lang>
}.start</syntaxhighlight>


Using the [http://www.sinatrarb.com/ sinatra] gem:
Using the [http://www.sinatrarb.com/ sinatra] gem:
<lang ruby>require 'sinatra'
<syntaxhighlight lang="ruby">require 'sinatra'
get("/") { "Goodbye, World!" }</lang>
get("/") { "Goodbye, World!" }</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>html "Hello World!"</lang>
<syntaxhighlight lang="runbasic">html "Hello World!"</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Basically no error handling. This web server will simply panic if there is any sort of error.
Basically no error handling. This web server will simply panic if there is any sort of error.
<lang rust>use std::net::{Shutdown, TcpListener};
<syntaxhighlight lang="rust">use std::net::{Shutdown, TcpListener};
use std::thread;
use std::thread;
use std::io::Write;
use std::io::Write;
Line 1,967: Line 1,967:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Salmon}}==
=={{header|Salmon}}==
<lang Salmon>use "http.salm" : "http.si";
<syntaxhighlight lang="salmon">use "http.salm" : "http.si";


/* Don't do any logging. */
/* Don't do any logging. */
Line 1,976: Line 1,976:


simple_http_server(8080, procedure(header, connection)
simple_http_server(8080, procedure(header, connection)
{ respond_text(connection, "Goodbye, World!"); });</lang>
{ respond_text(connection, "Goodbye, World!"); });</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
{{Trans|Java}}It shows that Scala can simply embed XML fragments.
{{Trans|Java}}It shows that Scala can simply embed XML fragments.
<lang Scala>import java.io.PrintWriter
<syntaxhighlight lang="scala">import java.io.PrintWriter
import java.net.ServerSocket
import java.net.ServerSocket


Line 2,004: Line 2,004:
sock.close()
sock.close()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{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].
The code below was inspired by the example code for the function [http://seed7.sourceforge.net/libraries/listener.htm#openInetListener%28in_integer%29 openInetListener].


<lang Seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "listener.s7i";
include "listener.s7i";


Line 2,027: Line 2,027:
close(sock);
close(sock);
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==


Using the low-level ''Socket'' object:
Using the low-level ''Socket'' object:
<lang ruby>var port = 8080;
<syntaxhighlight lang="ruby">var port = 8080;
var protocol = Socket.getprotobyname("tcp");
var protocol = Socket.getprotobyname("tcp");
 
 
Line 2,055: Line 2,055:
"<body>Goodbye, world!</body></html>\r\n");
"<body>Goodbye, world!</body></html>\r\n");
client.close;
client.close;
}</lang>
}</syntaxhighlight>


A more friendly interface, using the ''IO::Socket::INET'' library:
A more friendly interface, using the ''IO::Socket::INET'' library:
<lang ruby>var inet = require('IO::Socket::INET');
<syntaxhighlight lang="ruby">var inet = require('IO::Socket::INET');


var sock = inet.new( LocalAddr => "127.0.0.1:8080",
var sock = inet.new( LocalAddr => "127.0.0.1:8080",
Line 2,071: Line 2,071:
"<body>Goodbye, world!</body></html>\r\n");
"<body>Goodbye, world!</body></html>\r\n");
client.close;
client.close;
}</lang>
}</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
starting server:
starting server:
<lang smalltalk>Smalltalk loadPackage:'stx:goodies/webServer'. "usually already loaded"
<syntaxhighlight lang="smalltalk">Smalltalk loadPackage:'stx:goodies/webServer'. "usually already loaded"
|myServer service|
|myServer service|


Line 2,089: Line 2,089:
service linkNames:#('/' ).
service linkNames:#('/' ).
service registerServiceOn: myServer.
service registerServiceOn: myServer.
myServer start.</lang>
myServer start.</syntaxhighlight>
Be aware that the above is an ad-hoc minimal scripting example.
Be aware that the above is an ad-hoc minimal scripting example.
Normally, a service subclass is used and
Normally, a service subclass is used and
Line 2,101: Line 2,101:
that includes a ZnServer class.
that includes a ZnServer class.
Here's the simplest solution to start a web server:
Here's the simplest solution to start a web server:
<lang smalltalk>(ZnServer startDefaultOn: 1701)
<syntaxhighlight lang="smalltalk">(ZnServer startDefaultOn: 1701)
onRequestRespond: [ :request |
onRequestRespond: [ :request |
ZnResponse ok: (ZnEntity text: 'Hello World!') ].</lang>
ZnResponse ok: (ZnEntity text: 'Hello World!') ].</syntaxhighlight>


To stop the server, use the following:
To stop the server, use the following:
<lang smalltalk>ZnServer stopDefault.</lang>
<syntaxhighlight lang="smalltalk">ZnServer stopDefault.</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world!" ) ;
val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world!" ) ;


Line 2,137: Line 2,137:
end handle x => (Socket.close listener; raise x)
end handle x => (Socket.close listener; raise x)
;
;
</syntaxhighlight>
</lang>
call - smlnj interpreter
call - smlnj interpreter
- serve (INetSock.TCP.socket()) 8080 ;
- serve (INetSock.TCP.socket()) 8080 ;
Line 2,155: Line 2,155:
===Tcl 8.x===
===Tcl 8.x===
This version is adapted from [http://wiki.tcl.tk/28414 the Tcler's Wiki].
This version is adapted from [http://wiki.tcl.tk/28414 the Tcler's Wiki].
<lang tcl>proc accept {chan addr port} {
<syntaxhighlight lang="tcl">proc accept {chan addr port} {
while {[gets $chan] ne ""} {}
while {[gets $chan] ne ""} {}
puts $chan "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n"
puts $chan "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n"
Line 2,162: Line 2,162:
}
}
socket -server accept 8080
socket -server accept 8080
vwait forever</lang>
vwait forever</syntaxhighlight>


===Jim Tcl===
===Jim Tcl===
Jim is a small footprint reimplementation of Tcl with modern features.
Jim is a small footprint reimplementation of Tcl with modern features.
<lang tcl>set s [socket stream.server 127.0.0.1:8080]
<syntaxhighlight lang="tcl">set s [socket stream.server 127.0.0.1:8080]
$s readable {
$s readable {
set client [$s accept]
set client [$s accept]
Line 2,173: Line 2,173:
$client close
$client close
}
}
vwait done</lang>
vwait done</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


<lang bash>while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; echo 'Hello, World!'; } | nc -l 8080; done</lang>
<syntaxhighlight lang="bash">while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; echo 'Hello, World!'; } | nc -l 8080; done</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==


<lang python>with server_socket socket :port 4000
<syntaxhighlight lang="python">with server_socket socket :port 4000
accepting client :from socket
accepting client :from socket
making stdout outfile+fd.client
making stdout outfile+fd.client
Line 2,187: Line 2,187:
prn "Content-type: text/plain"
prn "Content-type: text/plain"
prn ""
prn ""
prn "Hello, world!"</lang>
prn "Hello, world!"</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|SpiderWren}}
{{libheader|SpiderWren}}
<lang ecmascript>import "web" for Routes, App
<syntaxhighlight lang="ecmascript">import "web" for Routes, App


Routes.GET("/") {
Routes.GET("/") {
Line 2,197: Line 2,197:
}
}


App.run(8080)</lang>
App.run(8080)</syntaxhighlight>


=={{header|X86-64 Assembly}}==
=={{header|X86-64 Assembly}}==
Line 2,203: Line 2,203:
This SHOULD assemble on both Linux and Windows.
This SHOULD assemble on both Linux and Windows.
(Tested on Arch, Don't have windows installed atm :[)
(Tested on Arch, Don't have windows installed atm :[)
<lang asm>
<syntaxhighlight lang="asm">
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Crossplatform(?) Web Server example using UASM's OO Language extention
;; Crossplatform(?) Web Server example using UASM's OO Language extention
Line 2,417: Line 2,417:
main endp
main endp
end
end
</syntaxhighlight>
</lang>


=={{header|zkl}}==
=={{header|zkl}}==
A threaded web server that returns "Goodbye, World!" for every request
A threaded web server that returns "Goodbye, World!" for every request
<lang zkl>const PORT=8080;
<syntaxhighlight lang="zkl">const PORT=8080;
const SERVLET_THREADS=4;
const SERVLET_THREADS=4;


Line 2,466: Line 2,466:
println("HTTP server started at http://",
println("HTTP server started at http://",
serverSocket.hostname, ":", serverSocket.port);
serverSocket.hostname, ":", serverSocket.port);
serverSocket.listen(jobPipe);</lang>
serverSocket.listen(jobPipe);</syntaxhighlight>