RingJavafor Ring

HTTP

A web server and a client of the JDK, in one Ring program: the handler is a Ring function.

What you will learn#

The program#

samples/UsingJava/tutorials/ch10_http.ring
# Tutorial 10: HTTP - a small web server of the JDK and a client, both in one Ring program
load "java.ring"

using {
	"java.lang"
	"java.net"
	"java.net.http"
	"java.nio.charset"
	"com.sun.net.httpserver"
}

HttpClient = new HttpClient
oFuture = NULL                      # global: futureReady() reads it
oClient = NULL
HttpRequest = new HttpRequest
BodyHandlers = new HttpResponseBodyHandlers      # BodyHandlers is a class inside HttpResponse: the names are joined
BodyPublishers = new HttpRequestBodyPublishers
URI = new URI
HttpServer = new HttpServer

# 1. the server: a handler is a Ring function that Java calls for each request
oServer = HttpServer.@create([ (new InetSocketAddress).@New(["127.0.0.1",0]) , 0 ])
oServer.createContext(["/hello","onHello"])
oServer.createContext(["/echo","onEcho"])
oServer.start()
nPort = oServer.getAddress().getPort()
cBase = "http://127.0.0.1:" + nPort
? "server started"

# 2. the client sends a GET request. The handler of the server is Ring code, and the Ring program is also the one that waits for the answer, so the request is sent
# with sendAsync and the program waits with jWaitUntil, which runs the handler meanwhile (send() would block the program and the handler could not run)
oClient = HttpClient.newHttpClient()
oRequest = HttpRequest.newBuilder().uri(URI.create(cBase + "/hello?name=Ring")).build()
oResponse = fetch(oRequest)
? oResponse.statusCode()
? oResponse.body()

# 3. a POST request with a body
oPost = HttpRequest.newBuilder().uri(URI.create(cBase + "/echo")).POST(BodyPublishers.ofString("text from the client")).build()
? fetch(oPost).body()

# 4. a missing path gives 404
oMissing = HttpRequest.newBuilder().uri(URI.create(cBase + "/nothing")).build()
? fetch(oMissing).statusCode()

oServer.stop(0)
? "server stopped"

# sends a request and waits for the response
func fetch oRequest
	oFuture = oClient.sendAsync([oRequest,BodyHandlers.ofString()])
	jWaitUntil("futureReady",10000)
	return oFuture.join()

func futureReady
	return oFuture.isDone()

# the handler gets an HttpExchange: read the request, write the answer
func onHello aArgs
	oExchange = aArgs[1]
	cQuery = oExchange.getRequestURI().getQuery()
	cName = "stranger"
	if left(cQuery,5) = "name="
		cName = substr(cQuery,6)
	ok
	reply(oExchange,"Hello, " + cName + "!")

func onEcho aArgs
	oExchange = aArgs[1]
	oBody = oExchange.getRequestBody()
	cText = (new String(oBody.readAllBytes())).toString()
	reply(oExchange,"echo: " + cText)

func reply oExchange,cText
	oBytes = new String(cText).@getBytes("UTF-8")
	oExchange.sendResponseHeaders(200,len(cText))
	oOut = oExchange.getResponseBody()
	oOut.write(oBytes)
	oOut.close()
Output
server started
200
Hello, Ring!
echo: text from the client
404
server stopped

How it works#

The server and the client live in the same Ring program. The handler is a Ring function that Java calls for each request, so it runs on the Ring thread. A blocking send() would stop that thread and the handler could never run: use sendAsync and jWaitUntil, which serves the callbacks while it waits.

Exercises#

  1. Add a path /time that answers with the current time.
  2. Send a header and read it in the handler.
  3. Count the requests the server got.

Next#

Hashing and encryption

RingJava - use Java classes and methods from Ring programs.