---
title: "Sending Arrow Tables Across a Socket"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Sending Arrow Tables Across a Socket}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

Arrow IPC provides a language-independent binary representation for Arrow
tables. This vignette uses two R sessions and sends an IPC stream directly
through a `socketR`-provided R connection adapter.

Install the optional dependency first:

```r
install.packages("arrow")
```

## Session 1: receive a table

Run this in the first R session:

```{r receiver, eval=FALSE}
library(socketR)
library(arrow)

server <- socket_create("inet", "stream")
peer <- NULL
on.exit({
  if (!is.null(peer) && socket_is_open(peer)) socket_close(peer)
  if (socket_is_open(server)) socket_close(server)
}, add = TRUE)

socket_reuse_address(server, TRUE)
socket_bind(server, "127.0.0.1", 45679L)
socket_listen(server)
cat("Waiting for an Arrow table...\n")

peer <- socket_accept(server)
peer_connection <- socket_connection(peer)
received <- read_ipc_stream(peer_connection)
print(received)
```

## Session 2: send a table

Run this in a second R session after Session 1 starts listening:

```{r sender, eval=FALSE}
library(socketR)
library(arrow)

client <- socket_create("inet", "stream")
on.exit(if (socket_is_open(client)) socket_close(client), add = TRUE)

table <- arrow_table(
  id = 1:3,
  name = c("Ada", "Grace", "Linus"),
  score = c(9.5, 10.0, 8.75)
)

socket_connect(client, "127.0.0.1", 45679L)
client_connection <- socket_connection(client)
write_ipc_stream(table, client_connection)
```

The receiving session obtains an Arrow `Table` without converting through
text or an R data frame. The same IPC bytes can be consumed by Arrow clients
in other languages, subject to the usual Arrow IPC compatibility rules. Arrow
may close the adapter after completing the stream; the underlying `socketR`
handle remains separately owned and should still be closed explicitly.
