The websockets package is an HTML 5 Websocket implementation for the R
language, based on the libwebsockets library written by Andy Green.
The websockets package is especially well-suited to lightweight
interaction between R and web scripting languages like Javascript.
Multiple simultaneous websocket connections are supported.
By 'lightweight' we mean that the library has few external dependencies and
is easily portable. More significantly, websockets lets Javascript and
other scripts embedded in web pages directly interact with R, bypassing
traditional middleware layers like .NET, Java, and web servers normally used
for such interaction.
The HTML 5 Websocket API is a modern socket-like communication protocol for the
web. Note that the HTML 5 Websocket API is still under development and may
change. Some browsers may not enable Websockets by default (including recent
versions of Firefox), but there are usually simple methods to enable the API.
Despite its developmental status, the API is presently widely supported: most
recent browsers support it and there are many available langauge
implementations.
This simple example illustrates a few features of websockets. For a
fancier demo that uses JSON, run the following in your R session:
demo('json', package='websockets')
The features illustrated in this example are:
- Each connected client has a data 'cookie' assigned to it which we
use here to store a client ID number. Try opening multiple browser pages
to http://localhost:7681 to see multiple connected clients.
- The R websocket service calls back to user-defined R functions when
various websocket events occur for each client. Here we use the 'establish'
callback function to assign and display the client ID on start up,
the 'receive' function to respond to input from each client, and
the 'broadcast' function to update the clients with a running counter.
- Press the 'SET' button to send the value in the text box to R.
The R websocket server receives the message and sets the counter for all
connected clients.
- Although not its primary function, the package can serve HTTP web pages like this one.