Type: | Package |
Title: | HTTP and WebSocket Server Library |
Version: | 1.6.16 |
Description: | Provides low-level socket and protocol support for handling HTTP and WebSocket requests directly from within R. 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. (See LICENSE file for libuv and http-parser license information.) |
License: | GPL-2 | GPL-3 | file LICENSE [expanded from: GPL (≥ 2) | file LICENSE] |
URL: | https://github.com/rstudio/httpuv |
BugReports: | https://github.com/rstudio/httpuv/issues |
Depends: | R (≥ 2.15.1) |
Imports: | later (≥ 0.8.0), promises, R6, Rcpp (≥ 1.0.7), utils |
Suggests: | callr, curl, jsonlite, testthat, websocket |
LinkingTo: | later, Rcpp |
Encoding: | UTF-8 |
RoxygenNote: | 7.3.2 |
SystemRequirements: | GNU make, zlib |
Collate: | 'RcppExports.R' 'httpuv.R' 'random_port.R' 'server.R' 'staticServer.R' 'static_paths.R' 'utils.R' |
NeedsCompilation: | yes |
Packaged: | 2025-04-15 17:47:41 UTC; cg334 |
Author: | Joe Cheng [aut], Winston Chang [aut, cre], Posit, PBC fnd [cph], Hector Corrada Bravo [ctb], Jeroen Ooms [ctb], Andrzej Krzemienski [cph] (optional.hpp), libuv project contributors [cph] (libuv library, see src/libuv/AUTHORS file), Joyent, Inc. and other Node contributors [cph] (libuv library, see src/libuv/AUTHORS file; and http-parser library, see src/http-parser/AUTHORS file), Niels Provos [cph] (libuv subcomponent: tree.h), Internet Systems Consortium, Inc. [cph] (libuv subcomponent: inet_pton and inet_ntop, contained in src/libuv/src/inet.c), Alexander Chemeris [cph] (libuv subcomponent: stdint-msvc2008.h (from msinttypes)), Google, Inc. [cph] (libuv subcomponent: pthread-fixes.c), Sony Mobile Communcations AB [cph] (libuv subcomponent: pthread-fixes.c), Berkeley Software Design Inc. [cph] (libuv subcomponent: android-ifaddrs.h, android-ifaddrs.c), Kenneth MacKay [cph] (libuv subcomponent: android-ifaddrs.h, android-ifaddrs.c), Emergya (Cloud4all, FP7/2007-2013, grant agreement no 289016) [cph] (libuv subcomponent: android-ifaddrs.h, android-ifaddrs.c), Steve Reid [aut] (SHA-1 implementation), James Brown [aut] (SHA-1 implementation), Bob Trower [aut] (base64 implementation), Alexander Peslyak [aut] (MD5 implementation), Trantor Standard Systems [cph] (base64 implementation), Igor Sysoev [cph] (http-parser) |
Maintainer: | Winston Chang <winston@posit.co> |
Repository: | CRAN |
Date/Publication: | 2025-04-16 08:00:06 UTC |
HTTP and WebSocket server
Description
HTTP and WebSocket server
Details
Allows R code to listen for and interact with HTTP and WebSocket clients, so you can serve web traffic directly out of your R process. Implementation is based on libuv and http-parser.
This is a low-level library that provides little more than network I/O and implementations of the HTTP and WebSocket protocols. For an easy way to create web applications, try Shiny instead.
Author(s)
Joe Cheng joe@rstudio.com
See Also
Examples
## Not run:
demo("echo", package="httpuv")
## End(Not run)
PipeServer class
Description
This class represents a server running one application that listens on a named pipe.
Methods
initialize(name, mask, app)
-
Create a new
PipeServer
object.app
is an httpuv application object as described instartServer
. getName()
Return the value of
name
that was passed toinitialize()
.getMask()
Return the value of
mask
that was passed toinitialize()
.stop()
Stops a running server.
isRunning()
Returns TRUE if the server is currently running.
getStaticPaths()
Returns a list of
staticPath
objects for the server.setStaticPath(..., .list = NULL)
Sets a static path for the current server. Each static path can be given as a named argument, or as an named item in
.list
. If there already exists a static path with the same name, it will be replaced.removeStaticPath(path)
Removes a static path with the given name.
getStaticPathOptions()
Returns a list of default
staticPathOptions
for the current server. Each static path will use these options by default, but they can be overridden for each static path.setStaticPathOption(..., .list = NULL)
Sets one or more static path options. Each option can be given as a named argument, or as a named item in
.list
.
Super class
httpuv::Server
-> PipeServer
Methods
Public methods
Inherited methods
Method new()
Usage
PipeServer$new(name, mask, app, quiet = FALSE)
Method getName()
Usage
PipeServer$getName()
Method getMask()
Usage
PipeServer$getMask()
See Also
Server class
Description
The Server
class is the parent class for WebServer
and
PipeServer
. This class defines an interface and is not meant to
be instantiated.
Methods
stop()
Stops a running server.
isRunning()
Returns TRUE if the server is currently running.
getStaticPaths()
Returns a list of
staticPath
objects for the server.setStaticPath(..., .list = NULL)
Sets a static path for the current server. Each static path can be given as a named argument, or as an named item in
.list
. If there already exists a static path with the same name, it will be replaced.removeStaticPath(path)
Removes a static path with the given name.
getStaticPathOptions()
Returns a list of default
staticPathOptions
for the current server. Each static path will use these options by default, but they can be overridden for each static path.setStaticPathOption(..., .list = NULL)
Sets one or more static path options. Each option can be given as a named argument, or as a named item in
.list
.
Methods
Public methods
Method stop()
Usage
Server$stop()
Method isRunning()
Usage
Server$isRunning()
Method getStaticPaths()
Usage
Server$getStaticPaths()
Method setStaticPath()
Usage
Server$setStaticPath(..., .list = NULL)
Method removeStaticPath()
Usage
Server$removeStaticPath(path)
Method getStaticPathOptions()
Usage
Server$getStaticPathOptions()
Method setStaticPathOption()
Usage
Server$setStaticPathOption(..., .list = NULL)
See Also
WebServer
and PipeServer
.
WebServer class
Description
This class represents a web server running one application. Multiple servers can be running at the same time.
Methods
initialize(host, port, app)
-
Create a new
WebServer
object.app
is an httpuv application object as described instartServer
. getHost()
Return the value of
host
that was passed toinitialize()
.getPort()
Return the value of
port
that was passed toinitialize()
.stop()
Stops a running server.
isRunning()
Returns TRUE if the server is currently running.
getStaticPaths()
Returns a list of
staticPath
objects for the server.setStaticPath(..., .list = NULL)
Sets a static path for the current server. Each static path can be given as a named argument, or as an named item in
.list
. If there already exists a static path with the same name, it will be replaced.removeStaticPath(path)
Removes a static path with the given name.
getStaticPathOptions()
Returns a list of default
staticPathOptions
for the current server. Each static path will use these options by default, but they can be overridden for each static path.setStaticPathOption(..., .list = NULL)
Sets one or more static path options. Each option can be given as a named argument, or as a named item in
.list
.
Super class
httpuv::Server
-> WebServer
Methods
Public methods
Inherited methods
Method new()
Usage
WebServer$new(host, port, app, quiet = FALSE)
Method getHost()
Usage
WebServer$getHost()
Method getPort()
Usage
WebServer$getPort()
See Also
Server
and PipeServer
.
WebSocket class
Description
A WebSocket
object represents a single WebSocket connection. The
object can be used to send messages and close the connection, and to receive
notifications when messages are received or the connection is closed.
Details
Note that this WebSocket class is different from the one provided by the package named websocket. This class is meant to be used on the server side, whereas the one in the websocket package is to be used as a client. The WebSocket class in httpuv has an older API than the one in the websocket package.
WebSocket objects should never be created directly. They are obtained by
passing an onWSOpen
function to startServer
.
Fields
request
-
The Rook request environment that opened the connection. This can be used to inspect HTTP headers, for example.
Methods
onMessage(func)
-
Registers a callback function that will be invoked whenever a message is received on this connection. The callback function will be invoked with two arguments. The first argument is
TRUE
if the message is binary andFALSE
if it is text. The second argument is either a raw vector (if the message is binary) or a character vector. onClose(func)
-
Registers a callback function that will be invoked when the connection is closed.
send(message)
-
Begins sending the given message over the websocket. The message must be either a raw vector, or a single-element character vector that is encoded in UTF-8.
close()
-
Closes the websocket connection.
Methods
Public methods
Method new()
Usage
WebSocket$new(handle, req)
Method onMessage()
Usage
WebSocket$onMessage(func)
Method onClose()
Usage
WebSocket$onClose(func)
Method send()
Usage
WebSocket$send(message)
Method close()
Usage
WebSocket$close(code = 1000L, reason = "")
Method clone()
The objects of this class are cloneable with this method.
Usage
WebSocket$clone(deep = FALSE)
Arguments
deep
Whether to make a deep clone.
Examples
## Not run:
# A WebSocket echo server that listens on port 8080
startServer("0.0.0.0", 8080,
list(
onHeaders = function(req) {
# Print connection headers
cat(capture.output(str(as.list(req))), sep = "\n")
},
onWSOpen = function(ws) {
cat("Connection opened.\n")
ws$onMessage(function(binary, message) {
cat("Server received message:", message, "\n")
ws$send(message)
})
ws$onClose(function() {
cat("Connection closed.\n")
})
}
)
)
## End(Not run)
URI encoding/decoding
Description
Encodes/decodes strings using URI encoding/decoding in the same way that web browsers do. The precise behaviors of these functions can be found at developer.mozilla.org: encodeURI, encodeURIComponent, decodeURI, decodeURIComponent
Usage
encodeURI(value)
encodeURIComponent(value)
decodeURI(value)
decodeURIComponent(value)
Arguments
value |
Character vector to be encoded or decoded. |
Details
Intended as a faster replacement for utils::URLencode()
and
utils::URLdecode()
.
encodeURI differs from encodeURIComponent in that the former will not encode
reserved characters: ;,/?:@&=+$
decodeURI differs from decodeURIComponent in that it will refuse to decode encoded sequences that decode to a reserved character. (If in doubt, use decodeURIComponent.)
For encodeURI
and encodeURIComponent
, input strings will be
converted to UTF-8 before URL-encoding.
Value
Encoded or decoded character vector of the same length as the
input value. decodeURI
and decodeURIComponent
will return
strings that are UTF-8 encoded.
Apply the value of .Random.seed to R's internal RNG state
Description
This function is needed in unusual cases where a C++ function calls
an R function which sets the value of .Random.seed
. This function
should be called at the end of the R function to ensure that the new value
.Random.seed
is preserved. Otherwise, Rcpp may overwrite it with a
previous value.
Usage
getRNGState()
Interrupt httpuv runloop
Description
Interrupts the currently running httpuv runloop, meaning
runServer
or service
will return control back to
the caller and no further tasks will be processed until those methods are
called again. Note that this may cause in-process uploads or downloads to be
interrupted in mid-request.
Usage
interrupt()
Check whether an address is IPv4 or IPv6
Description
Given an IP address, this checks whether it is an IPv4 or IPv6 address.
Usage
ipFamily(ip)
Arguments
ip |
A single string representing an IP address. |
Value
For IPv4 addresses, 4
; for IPv6 addresses, 6
. If the address is
neither, -1
.
Examples
ipFamily("127.0.0.1") # 4
ipFamily("500.0.0.500") # -1
ipFamily("500.0.0.500") # -1
ipFamily("::") # 6
ipFamily("::1") # 6
ipFamily("fe80::1ff:fe23:4567:890a") # 6
List all running httpuv servers
Description
This returns a list of all running httpuv server applications.
Usage
listServers()
Get and set logging level
Description
The logging level for httpuv can be set to report differing levels of
information. Possible logging levels (from least to most information
reported) are: "OFF"
, "ERROR"
, "WARN"
, "INFO"
, or
"DEBUG"
. The default level is ERROR
.
Usage
logLevel(level = NULL)
Arguments
level |
The logging level. Must be one of |
Value
If level=NULL
, then this returns the current logging level. If
level
is any other value, then this returns the previous logging
level, from before it is set to the new value.
Find an open TCP port
Description
Finds a random available TCP port for listening on, within a specified range of ports. The default range of ports to check is 1024 to 49151, which is the set of TCP User Ports. This function automatically excludes some ports which are considered unsafe by web browsers.
Usage
randomPort(min = 1024L, max = 49151L, host = "127.0.0.1", n = 20)
Arguments
min |
Minimum port number. |
max |
Maximum port number. |
host |
A string that is a valid IPv4 or IPv6 address that is owned by
this server, which the application will listen on. |
n |
Number of ports to try before giving up. |
Value
A port that is available to listen on.
Examples
## Not run:
s <- startServer("127.0.0.1", randomPort(), list())
browseURL(paste0("http://127.0.0.1:", s$getPort()))
s$stop()
## End(Not run)
Convert raw vector to Base64-encoded string
Description
Converts a raw vector to its Base64 encoding as a single-element character vector.
Usage
rawToBase64(x)
Arguments
x |
A raw vector. |
Examples
set.seed(100)
result <- rawToBase64(as.raw(runif(19, min=0, max=256)))
stopifnot(identical(result, "TkGNDnd7z16LK5/hR2bDqzRbXA=="))
Run a server
Description
This is a convenience function that provides a simple way to call
startServer
, service
, and
stopServer
in the correct sequence. It does not return unless
interrupted or an error occurs.
Usage
runServer(host, port, app, interruptIntervalMs = NULL)
Arguments
host |
A string that is a valid IPv4 or IPv6 address that is owned by
this server, which the application will listen on. |
port |
A number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and macOS, port numbers smaller than 1024 require root privileges. |
app |
A collection of functions that define your application. See
|
interruptIntervalMs |
Deprecated (last used in httpuv 1.3.5). |
Details
If you have multiple hosts and/or ports to listen on, call the individual
functions instead of runServer
.
See Also
startServer
, service
,
stopServer
Examples
## Not run:
# A very basic application
runServer("0.0.0.0", 5000,
list(
call = function(req) {
list(
status = 200L,
headers = list(
'Content-Type' = 'text/html'
),
body = "Hello world!"
)
}
)
)
## End(Not run)
Serve a directory
Description
runStaticServer()
provides a convenient interface to start a server to host
a single static directory, either in the foreground or the background.
Usage
runStaticServer(
dir = getwd(),
host = "127.0.0.1",
port = NULL,
...,
background = FALSE,
browse = interactive()
)
Arguments
dir |
The directory to serve. Defaults to the current working directory. |
host |
A string that is a valid IPv4 address that is owned by this
server, or |
port |
A number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and macOS, port numbers smaller than 1024 require root privileges. |
... |
Arguments passed on to
|
background |
Whether to run the server in the background. By default,
the server runs in the foreground and blocks the R console. You can stop
the server by interrupting it with When |
browse |
Whether to automatically open the served directory in a web
browser. Defaults to |
Value
Starts a server on the specified host and port. By default the
server runs in the foreground and is accessible at http://127.0.0.1:7446
.
When background = TRUE
, the server
object is returned invisibly.
See Also
runServer()
provides a similar interface for running a dynamic
app server. Both runStaticServer()
and runServer()
are built on top of
startServer()
, service()
and stopServer()
. Learn more about httpuv
servers in startServer()
.
Examples
website_dir <- system.file("example-static-site", package = "httpuv")
runStaticServer(dir = website_dir)
Process requests
Description
Process HTTP requests and WebSocket messages. If there is nothing on R's call
stack – if R is sitting idle at the command prompt – it is not necessary to
call this function, because requests will be handled automatically. However,
if R is executing code, then requests will not be handled until either the
call stack is empty, or this function is called (or alternatively,
run_now
is called).
Usage
service(timeoutMs = ifelse(interactive(), 100, 1000))
Arguments
timeoutMs |
Approximate number of milliseconds to run before returning. It will return this duration has elapsed. If 0 or Inf, then the function will continually process requests without returning unless an error occurs. If NA, performs a non-blocking run without waiting. |
Details
In previous versions of httpuv (1.3.5 and below), even if a server created by
startServer
exists, no requests were serviced unless and until
service
was called.
This function simply calls run_now()
, so if your
application schedules any later
callbacks, they will be
invoked.
Examples
## Not run:
while (TRUE) {
service()
}
## End(Not run)
Create an HTTP/WebSocket daemonized server (deprecated)
Description
This function will be removed in a future release of httpuv. It is simply a
wrapper for startServer
. In previous versions of httpuv (1.3.5
and below), startServer
ran applications in the foreground and
startDaemonizedServer
ran applications in the background, but now both
of them run applications in the background.
Usage
startDaemonizedServer(host, port, app, quiet = FALSE)
Arguments
host |
A string that is a valid IPv4 address that is owned by this
server, or |
port |
A number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and macOS, port numbers smaller than 1024 require root privileges. |
app |
A collection of functions that define your application. See Details. |
quiet |
If |
Create an HTTP/WebSocket server
Description
Creates an HTTP/WebSocket server on the specified host and port.
Usage
startServer(host, port, app, quiet = FALSE)
startPipeServer(name, mask, app, quiet = FALSE)
Arguments
host |
A string that is a valid IPv4 address that is owned by this
server, or |
port |
A number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and macOS, port numbers smaller than 1024 require root privileges. |
app |
A collection of functions that define your application. See Details. |
quiet |
If |
name |
A string that indicates the path for the domain socket (on Unix-like systems) or the name of the named pipe (on Windows). |
mask |
If non- |
Details
startServer
binds the specified port and listens for
connections on an thread running in the background. This background thread
handles the I/O, and when it receives a HTTP request, it will schedule a
call to the user-defined R functions in app
to handle the request.
This scheduling is done with later()
. When the R call
stack is empty – in other words, when an interactive R session is sitting
idle at the command prompt – R will automatically run the scheduled calls.
However, if the call stack is not empty – if R is evaluating other R code
– then the callbacks will not execute until either the call stack is
empty, or the run_now()
function is called. This
function tells R to execute any callbacks that have been scheduled by
later()
. The service()
function is
essentially a wrapper for run_now()
.
In older versions of httpuv (1.3.5 and below), it did not use a background
thread for I/O, and when this function was called, it did not accept
connections immediately. It was necessary to call service
repeatedly in order to actually accept and handle connections.
If the port cannot be bound (most likely due to permissions or because it is already bound), an error is raised.
The application can also specify paths on the filesystem which will be
served from the background thread, without invoking $call()
or
$onHeaders()
. Files served this way will be only use a C++ code,
which is faster than going through R, and will not be blocked when R code
is executing. This can greatly improve performance when serving static
assets.
The app
parameter is where your application logic will be provided
to the server. This can be a list, environment, or reference class that
contains the following methods and fields:
call(req)
Process the given HTTP request, and return an HTTP response (see Response Values). This method should be implemented in accordance with the Rook specification. Note that httpuv augments
req
with an additional item,req$HEADERS
, which is a named character vector of request headers.onHeaders(req)
Optional. Similar to
call
, but occurs when headers are received. ReturnNULL
to continue normal processing of the request, or a Rook response to send that response, stop processing the request, and ask the client to close the connection. (This can be used to implement upload size limits, for example.)onWSOpen(ws)
Called back when a WebSocket connection is established. The given object can be used to be notified when a message is received from the client, to send messages to the client, etc. See
WebSocket
.staticPaths
-
A named list of paths that will be served without invoking
call()
oronHeaders
. The name of each one is the URL path, and the value is either a string referring to a local path, or an object created by thestaticPath
function. staticPathOptions
-
A set of default options to use when serving static paths. If not set or
NULL
, then it will use the result from callingstaticPathOptions()
with no arguments.
The startPipeServer
variant can be used instead of
startServer
to listen on a Unix domain socket or named pipe rather
than a TCP socket (this is not common).
Value
A handle for this server that can be passed to
stopServer
to shut the server down.
A WebServer
or PipeServer
object.
Response Values
The call
function is expected to return a list containing the
following, which are converted to an HTTP response and sent to the client:
status
A numeric HTTP status code, e.g.
200
or404L
.headers
A named list of HTTP headers and their values, as strings. This can also be missing, an empty list, or
NULL
, in which case no headers (other than theDate
andContent-Length
headers, as required) will be added.body
A string (or
raw
vector) to be sent as the body of the HTTP response. This can also be omitted or set toNULL
to avoid sending any body, which is useful for HTTP1xx
,204
, and304
responses, as well as responses toHEAD
requests.
See Also
stopServer
, runServer
,
listServers
, stopAllServers
.
Examples
## Not run:
# A very basic application
s <- startServer("0.0.0.0", 5000,
list(
call = function(req) {
list(
status = 200L,
headers = list(
'Content-Type' = 'text/html'
),
body = "Hello world!"
)
}
)
)
s$stop()
# An application that serves static assets at the URL paths /assets and /lib
s <- startServer("0.0.0.0", 5000,
list(
call = function(req) {
list(
status = 200L,
headers = list(
'Content-Type' = 'text/html'
),
body = "Hello world!"
)
},
staticPaths = list(
"/assets" = "content/assets/",
"/lib" = staticPath(
"content/lib",
indexhtml = FALSE
),
# This subdirectory of /lib should always be handled by the R code path
"/lib/dynamic" = excludeStaticPath()
),
staticPathOptions = staticPathOptions(
indexhtml = TRUE
)
)
)
s$stop()
## End(Not run)
Create a staticPath object
Description
The staticPath
function creates a staticPath
object. Note that
if any of the arguments (other than path
) are NULL
, then that
means that for this particular static path, it should inherit the behavior
from the staticPathOptions set for the application as a whole.
Usage
staticPath(
path,
indexhtml = NULL,
fallthrough = NULL,
html_charset = NULL,
headers = NULL,
validation = NULL
)
excludeStaticPath()
Arguments
path |
The local path. |
indexhtml |
If an index.html file is present, should it be served up when the client requests the static path or any subdirectory? |
fallthrough |
With the default value, |
html_charset |
When HTML files are served, the value that will be
provided for |
headers |
Additional headers and values that will be included in the response. |
validation |
An optional validation pattern. Presently, the only type of
validation supported is an exact string match of a header. For example, if
|
Details
The excludeStaticPath
function tells the application to ignore a
particular path for static serving. This is useful when you want to include a
path for static serving (like "/"
) but then exclude a subdirectory of
it (like "/dynamic"
) so that the subdirectory will always be passed to
the R code for handling requests. excludeStaticPath
can be used not
only for directories; it can also exclude specific files.
See Also
Create options for static paths
Description
Create options for static paths
Usage
staticPathOptions(
indexhtml = TRUE,
fallthrough = FALSE,
html_charset = "utf-8",
headers = list(),
validation = character(0),
exclude = FALSE
)
Arguments
indexhtml |
If an index.html file is present, should it be served up when the client requests the static path or any subdirectory? |
fallthrough |
With the default value, |
html_charset |
When HTML files are served, the value that will be
provided for |
headers |
Additional headers and values that will be included in the response. |
validation |
An optional validation pattern. Presently, the only type of
validation supported is an exact string match of a header. For example, if
|
exclude |
Should this path be excluded from static serving? (This is
only to be used internally, for |
Stop all servers
Description
This will stop all applications which were created by
startServer
or startPipeServer
.
Usage
stopAllServers()
See Also
stopServer
to stop a specific server.
Stop a running daemonized server in Unix environments (deprecated)
Description
This function will be removed in a future release of httpuv. Instead, use
stopServer
.
Usage
stopDaemonizedServer(server)
Arguments
server |
A server object that was previously returned from
|
Stop a server
Description
Given a server object that was returned from a previous invocation of
startServer
or startPipeServer
, this closes all
open connections for that server and unbinds the port.
Usage
stopServer(server)
Arguments
server |
A server object that was previously returned from
|
See Also
stopAllServers
to stop all servers.