• Stars
    star
    217
  • Rank 175,695 (Top 4 %)
  • Language
    C
  • License
    Other
  • Created about 11 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP and WebSocket server package for R

httpuv: HTTP and WebSocket server library for R

R build status

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.

Installing

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")
remotes::install_github("rstudio/httpuv")

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

httpuv may optionally be built using a libuv system package, which you can install prior to installing the R package. It goes by different names on different package managers: libuv1-dev (deb), libuv-devel (rpm), libuv (brew). Version 1.43 or greater is required. If libuv is not found on the system, it will be built from source along with the R package.

Basic Usage

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)

s <- startServer(host = "0.0.0.0", port = 8080,
  app = list(
    call = function(req) {
      body <- paste0("Time: ", Sys.time(), "<br>Path requested: ", req$PATH_INFO)
      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:

s$stop()

Or, to stop all running httpuv servers:

stopAllServers()

Static paths

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:

s <- startServer("0.0.0.0", 8080,
  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.

s <- startServer("0.0.0.0", 8080,
  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)
    )
  )
)

WebSocket server

httpuv also can handle WebSocket connections. For example, this app acts as a WebSocket echo server:

s <- startServer("127.0.0.1", 8080,
  list(
    onWSOpen = function(ws) {
      # The ws object is a WebSocket object
      cat("Server connection opened.\n")

      ws$onMessage(function(binary, message) {
        cat("Server received message:", message, "\n")
        ws$send(message)
      })
      ws$onClose(function() {
        cat("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.

ws <- websocket::WebSocket$new("ws://127.0.0.1:8080/")
ws$onMessage(function(event) {
  cat("Client received message:", event$data, "\n")
})

# Wait for a moment before running next line
ws$send("hello world")

# Close client
ws$close()

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.


Debugging builds

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:

withr::with_makevars(
  c(PKG_CPPFLAGS="-DDEBUG_TRACE -DDEBUG_THREAD -UNDEBUG"), {
    devtools::install_github("rstudio/httpuv")
  }, assignment = "+="
)

© 2013-2020 RStudio, Inc.

More Repositories

1

cheatsheets

Posit Cheat Sheets - Can also be found at https://posit.co/resources/cheatsheets/.
TeX
5,540
star
2

shiny

Easy interactive web applications with R
R
5,209
star
3

rstudio

RStudio is an integrated development environment (IDE) for R
Java
4,432
star
4

bookdown

Authoring Books and Technical Documents with R Markdown
JavaScript
3,613
star
5

rmarkdown

Dynamic Documents for R
R
2,737
star
6

shiny-examples

JavaScript
1,927
star
7

gt

Easily generate information-rich, publication-quality tables from R
R
1,892
star
8

blogdown

Create Blogs and Websites with R Markdown
R
1,694
star
9

reticulate

R Interface to Python
R
1,604
star
10

webinars

Code and slides for RStudio webinars
HTML
1,510
star
11

rticles

LaTeX Journal Article Templates for R Markdown
TeX
1,402
star
12

plumber

Turn your R code into a web API.
R
1,355
star
13

tensorflow

TensorFlow for R
R
1,313
star
14

renv

renv: Project environments for R.
R
953
star
15

pagedown

Paginate the HTML Output of R Markdown with CSS for Print
R
861
star
16

shinydashboard

Shiny Dashboarding framework
CSS
852
star
17

pointblank

Data quality assessment and metadata reporting for data frames and database tables
R
824
star
18

keras

R Interface to Keras
R
818
star
19

flexdashboard

Easy interactive dashboards for R
JavaScript
788
star
20

leaflet

R Interface to Leaflet Maps
JavaScript
784
star
21

rmarkdown-book

R Markdown: The Definitive Guide (published by Chapman & Hall/CRC in July 2018)
RMarkdown
738
star
22

ggvis

Interactive grammar of graphics for R
R
709
star
23

shiny-server

Host Shiny applications over the web.
JavaScript
700
star
24

rstudio-conf

Materials for rstudio::conf
HTML
696
star
25

learnr

Interactive Tutorials with R Markdown
R
695
star
26

RStartHere

A guide to some of the most useful R Packages that we know about
R
656
star
27

py-shiny

Shiny for Python
Python
627
star
28

DT

R Interface to the jQuery Plug-in DataTables
JavaScript
581
star
29

rmarkdown-cookbook

R Markdown Cookbook. A range of tips and tricks to make better use of R Markdown.
RMarkdown
562
star
30

blastula

Easily send great-looking HTML email messages from R
R
522
star
31

r2d3

R Interface to D3 Visualizations
R
513
star
32

bookdown-demo

A minimal book example using bookdown
CSS
476
star
33

hex-stickers

RStudio hex stickers
R
434
star
34

distill

Distill for R Markdown
HTML
416
star
35

bslib

Tools for theming Shiny and R Markdown via Bootstrap 3, 4, or 5.
SCSS
414
star
36

packrat

Packrat is a dependency management system for R
R
394
star
37

tufte

Tufte Styles for R Markdown Documents
R
385
star
38

dygraphs

R interface to dygraphs
JavaScript
361
star
39

revealjs

R Markdown Format for reveal.js Presentations
JavaScript
316
star
40

pins-r

Pin, Discover and Share Resources
R
299
star
41

fontawesome

Easily insert FontAwesome icons into R Markdown docs and Shiny apps
R
287
star
42

profvis

Visualize R profiling data
JavaScript
285
star
43

crosstalk

Inter-htmlwidget communication for R (with and without Shiny)
JavaScript
284
star
44

config

config package for R
R
247
star
45

pool

Object Pooling in R
R
242
star
46

thematic

Theme ggplot2, lattice, and base graphics based on a few simple settings.
R
237
star
47

Intro

Course materials for "Introduction to Data Science with R", a video course by RStudio and O'Reilly Media
R
234
star
48

tinytex-releases

Windows/macOS/Linux binaries and installation methods of TinyTeX
PowerShell
226
star
49

shinytest

Automated testing for shiny apps
JavaScript
222
star
50

nomnoml

Sassy 'UML' Diagrams for R
JavaScript
216
star
51

shinymeta

Record and expose Shiny app logic using metaprogramming
R
212
star
52

htmltools

Tools for HTML generation and output
R
201
star
53

shinyuieditor

A GUI for laying out a Shiny application that generates clean and human-readable UI code
JavaScript
200
star
54

promises

A promise library for R
R
193
star
55

vetiver-r

Version, share, deploy, and monitor models
R
174
star
56

rstudioapi

Safely access RStudio's API (when available)
R
161
star
57

gradethis

Tools for teachers to use with learnr
R
159
star
58

concept-maps

Concept maps for all things data science
HTML
158
star
59

master-the-tidyverse

Course contents for Master the Tidyverse
156
star
60

shinythemes

Themes for Shiny
R
152
star
61

ShinyDeveloperConference

Materials collected from the First Shiny Developer Conference Palo Alto, CA January 30-31 2016
HTML
152
star
62

chromote

Chrome Remote Interface for R
R
145
star
63

shiny-gallery

Code and other documentation for apps in the Shiny Gallery ✨
HTML
140
star
64

sortable

R htmlwidget for Sortable.js
R
124
star
65

rsconnect

Publish Shiny Applications, RMarkdown Documents, Jupyter Notebooks, Plumber APIs, and more
R
120
star
66

reactlog

Shiny Reactivity Visualizer
JavaScript
119
star
67

redx

dynamic nginx configuration
Lua
118
star
68

bigdataclass

Two-day workshop that covers how to use R to interact databases and Spark
R
114
star
69

r-system-requirements

System requirements for R packages
Shell
111
star
70

shinyapps

Deploy Shiny applications to ShinyApps
110
star
71

webshot2

Take screenshots of web pages from R
R
109
star
72

shinyloadtest

Tools for load testing Shiny applications
HTML
108
star
73

shinyvalidate

Input validation package for the Shiny web framework
JavaScript
108
star
74

r-docker

Docker images for R
Dockerfile
105
star
75

miniUI

R
102
star
76

sass

Sass compiler package for R
C++
102
star
77

shinytest2

R
98
star
78

keras-customer-churn

Customer Churn Shiny Application
R
98
star
79

r-builds

an opinionated environment for compiling R
Shell
91
star
80

r-manuals

A re-styled version of the R manuals
R
85
star
81

addinexamples

An R package showcasing how RStudio addins can be registered and used.
R
85
star
82

shinyapps-package-dependencies

Collection of bash scripts that install R package system dependencies
R
74
star
83

markdown

The first generation of Markdown rendering for R (born in 2012). Originally based on the C library sundown. Now based on commonmark. Note that this package is markdown, not *rmarkdown*.
R
72
star
84

R-Websockets

HTML 5 Websockets implementation for R
R
68
star
85

webdriver

WebDriver client in R
R
68
star
86

beyond-dashboard-fatigue

Materials for the RStudio webinar 'Beyond Dashboard Fatigue'
R
66
star
87

cloudml

R interface to Google Cloud Machine Learning Engine
R
65
star
88

shinylive

Run Shiny on Python (compiled to wasm) in the browser
TypeScript
61
star
89

rstudio-conf-2022-program

rstudio::conf(2022, "program")
R
61
star
90

rstudio-docker-products

Docker images for RStudio Professional Products
Just
59
star
91

bookdown.org

Source documents to generate the bookdown.org website
R
59
star
92

education.rstudio.com

CSS
57
star
93

tfestimators

R interface to TensorFlow Estimators
R
57
star
94

vetiver-python

Version, share, deploy, and monitor models.
Python
55
star
95

tfprobability

R interface to TensorFlow Probability
R
54
star
96

sparkDemos

HTML
53
star
97

shiny-incubator

Examples and ideas that don't belong in the core Shiny package and aren't officially supported.
JavaScript
53
star
98

connections

https://rstudio.github.io/connections/
R
52
star
99

swagger

Swagger is a collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
HTML
51
star
100

leaflet.mapboxgl

Extends the R Leaflet package with a Mapbox GL JS plugin to allow easy drawing of vector tile layers.
R
49
star