Learn R Programming

ambiorix (version 2.2.0)

Websocket: Websocket

Description

Handle websocket messages.

Arguments

Value

A Websocket object.

Methods


Method new()

Usage

Websocket$new(ws)

Arguments

ws

Details

Constructor


Method send()

Usage

Websocket$send(name, message)

Arguments

name

Name, identifier, of the message.

message

Content of the message, anything that can be serialised to JSON.

Details

Send a message


Method print()

Usage

Websocket$print()

Details

Print


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

Run this code
# create an Ambiorix app with websocket support:
if (interactive()) {
  library(ambiorix)

  home_get <- function(req, res) {
    res$send("hello, world!")
  }

  greeting_ws_handler <- function(msg, ws) {
    cat("Received message:", "\n")
    print(msg)
    ws$send("greeting", "Hello from the server!")
  }

  app <- Ambiorix$new(port = 8080)
  app$get("/", home_get)
  app$receive("greeting", greeting_ws_handler)
  app$start()
}

# create websocket client from another R session:
if (interactive()) {
  client <- websocket::WebSocket$new("ws://127.0.0.1:8080", autoConnect = FALSE)

  client$onOpen(function(event) {
    cat("Connection opened\n")

    msg <- list(
      isAmbiorix = TRUE, # __MUST__ be set!
      name = "greeting",
      message = "Hello from the client!"
    )

    # serialise:
    msg <- yyjsonr::write_json_str(msg, auto_unbox = TRUE)

    client$send(msg)
  })

  client$onMessage(function(event) {
    cat("Received message from server:", event$data, "\n")
  })

  client$connect()
}

Run the code above in your browser using DataLab