httpuv provides low-level socket and protocol support for handling HTTP and WebSocket requests directly from within R. It uses a multithreaded architecture, where I/O is handled on one thread, and the R callbacks are handled on another.
It is primarily intended as a building block for other packages, rather than making it particularly easy to create complete web applications using httpuv alone. httpuv is built on top of the libuv and http-parser C libraries, both of which were developed by Joyent, Inc.
You can install the stable version from CRAN, or the development version using remotes:
# install from CRAN
install.packages("httpuv")
# or if you want to test the development version here
if (!require("remotes")) install.packages("remotes")
::install_github("rstudio/httpuv") remotes
Since httpuv contains C code, you’ll need to make sure you’re set up to install packages with compiled code. Follow the instructions at http://www.rstudio.com/ide/docs/packages/prerequisites
This is a basic web server that listens on port 8080 and responds to HTTP requests with a web page containing the current system time and the path of the request:
library(httpuv)
<- startServer(host = "0.0.0.0", port = 8080,
s app = list(
call = function(req) {
<- paste0("Time: ", Sys.time(), "<br>Path requested: ", req$PATH_INFO)
body list(
status = 200L,
headers = list('Content-Type' = 'text/html'),
body = body
)
}
) )
Note that when host
is 0.0.0.0, it listens on all
network interfaces. If host
is 127.0.0.1, it will only
listen to connections from the local host.
The startServer()
function takes an app object,
which is a named list with functions that are invoked in response to
certain events. In the example above, the list contains a function
call
. This function is invoked when a complete HTTP request
is received by the server, and it is passed an environment object
req
, which contains information about HTTP request.
req$PATH_INFO
is the path requested (if the request was for
http://127.0.0.1:8080/foo, it would be "/foo"
).
The call
function is expected to return a list
containing status
, headers
, and
body
. That list will be transformed into a HTTP response
and sent to the client.
To stop the server:
$stop() s
Or, to stop all running httpuv servers:
stopAllServers()
A httpuv server application can serve up files on disk. This happens entirely within the I/O thread, so doing so will not block or be blocked by activity in the main R thread.
To serve a path, use staticPaths
in the app. This will
serve the www/
subdirectory of the current directory (from
when startServer
is called) as the root of the web
path:
<- startServer("0.0.0.0", 8080,
s app = list(
staticPaths = list("/" = "www/")
) )
By default, if a file named index.html
exists in the
directory, it will be served when /
is requested.
staticPaths
can be combined with call
. In
this example, the web paths /assets
and /lib
are served from disk, but requests for any other paths go through the
call
function.
<- startServer("0.0.0.0", 8080,
s list(
call = function(req) {
list(
status = 200L,
headers = list(
'Content-Type' = 'text/html'
),body = "Hello world!"
)
},staticPaths = list(
"/assets" = "content/assets/",
# Don't use index.html for /lib
"/lib" = staticPath("content/lib", indexhtml = FALSE)
)
) )
httpuv also can handle WebSocket connections. For example, this app acts as a WebSocket echo server:
<- startServer("127.0.0.1", 8080,
s list(
onWSOpen = function(ws) {
# The ws object is a WebSocket object
cat("Server connection opened.\n")
$onMessage(function(binary, message) {
wscat("Server received message:", message, "\n")
$send(message)
ws
})$onClose(function() {
wscat("Server connection closed.\n")
})
}
) )
To test it out, you can connect to it using the websocket package (which provides a WebSocket client). You can do this from the same R process or a different one.
<- websocket::WebSocket$new("ws://127.0.0.1:8080/")
ws $onMessage(function(event) {
wscat("Client received message:", event$data, "\n")
})
# Wait for a moment before running next line
$send("hello world")
ws
# Close client
$close() ws
Note that both the httpuv and websocket packages provide a class
named WebSocket
; however, in httpuv, that class acts as a
server, and in websocket, it acts as a client. They also have different
APIs. For more information about the WebSocket client package, see the
project page.
httpuv can be built with debugging options enabled. This can be done by uncommenting these lines in src/Makevars, and then installing. The first one enables thread assertions, to ensure that code is running on the correct thread; if not. The second one enables tracing statements: httpuv will print lots of messages when various events occur.
PKG_CPPFLAGS += -DDEBUG_THREAD -UNDEBUG
PKG_CPPFLAGS += -DDEBUG_TRACE
To install it directly from GitHub with these options, you can use
with_makevars
, like this:
::with_makevars(
withrc(PKG_CPPFLAGS="-DDEBUG_TRACE -DDEBUG_THREAD -UNDEBUG"), {
::install_github("rstudio/httpuv")
devtoolsassignment = "+="
}, )
© 2013-2020 RStudio, Inc.