% Generated by roxygen2: do not edit by hand % Please edit documentation in R/server.R \name{handler_ws} \alias{handler_ws} \title{Create WebSocket Handler} \usage{ handler_ws( path, on_message, on_open = NULL, on_close = NULL, textframes = FALSE ) } \arguments{ \item{path}{URI path for WebSocket connections (e.g., "/ws").} \item{on_message}{Function called when a message is received. Signature: \verb{function(ws, data)} where \code{ws} is the connection object and \code{data} is the message. Use \code{ws$send()} to send responses; the return value is ignored.} \item{on_open}{[default NULL] Function called when a connection opens. Signature: \verb{function(ws, req)} where \code{req} is a list with \code{uri} (character) and \code{headers} (named character vector) from the HTTP upgrade request.} \item{on_close}{[default NULL] Function called when a connection closes. Signature: \verb{function(ws)}} \item{textframes}{[default FALSE] Logical, use text frames instead of binary. When TRUE: incoming \code{data} is character, outgoing data should be character. When FALSE: incoming \code{data} is raw vector, outgoing data should be raw vector.} } \value{ A handler object for use with \code{\link[=http_server]{http_server()}}. } \description{ Creates a WebSocket handler for use with \code{\link[=http_server]{http_server()}}. } \section{Connection Object}{ The \code{ws} object passed to callbacks has the following fields and methods: \itemize{ \item \code{ws$send(data)}: Send a message to the client. \code{data} can be a raw vector or character string. Returns 0 on success, or an error code on failure (e.g., if the connection is closed). \item \code{ws$close()}: Close the connection. \item \code{ws$id}: Unique integer identifier for this connection. No two connections on the same server will share an ID, even across different handlers, making IDs safe to use as keys in a shared data structure. } } \examples{ # Simple echo server h <- handler_ws("/ws", function(ws, data) ws$send(data)) # With connection tracking clients <- list() h <- handler_ws( "/chat", on_message = function(ws, data) { # Broadcast to all for (client in clients) client$send(data) }, on_open = function(ws, req) { clients[[as.character(ws$id)]] <<- ws }, on_close = function(ws) { clients[[as.character(ws$id)]] <<- NULL }, textframes = TRUE ) }