# webrtc

> WebRTC peer connections in Langoost — SDP offer/answer, data channels, and connection-state callbacks, with ICE, STUN, and DTLS-SRTP handled internally.

# webrtc

The `webrtc` module (built on pion/webrtc) manages peer connections and data
channels. DTLS-SRTP, ICE, and STUN are handled internally — you drive the SDP
offer/answer exchange and read/write data channels. Peers are referenced by an
integer **handle**. Import it with `import webrtc`.

## Functions

| Function | Signature | Description |
| --- | --- | --- |
| `newPeer` | `webrtc.newPeer(opts?) → int` | Create a peer connection; `opts` may include `iceServers`. Returns a handle |
| `createOffer` | `webrtc.createOffer(h: int) → string` | Create an SDP offer |
| `createAnswer` | `webrtc.createAnswer(h: int) → string` | Create an SDP answer |
| `setRemoteDescription` | `webrtc.setRemoteDescription(h: int, sdp: string, type: string) → bool` | Apply the remote SDP (`type` is `"offer"` or `"answer"`) |
| `localDescription` | `webrtc.localDescription(h: int) → object` | The local description as `{sdp, type}`, or `nil` |
| `addDataChannel` | `webrtc.addDataChannel(h: int, label: string, fn) → int` | Open a data channel; `fn(msg)` fires on each message. Returns a channel id |
| `sendData` | `webrtc.sendData(h: int, channelId: int, payload: string) → bool` | Send on a data channel |
| `onDataChannel` | `webrtc.onDataChannel(h: int, fn)` | `fn(channelId, label)` fires when the remote opens a channel |
| `onConnectionStateChange` | `webrtc.onConnectionStateChange(h: int, fn)` | `fn(state)` fires on connection-state changes |
| `close` | `webrtc.close(h: int) → bool` | Close the peer connection |

Callbacks fire safely against your program even though pion delivers them from
its own goroutines — see [native callbacks](/docs/architecture#native-callbacks).

## Example

```goost
import webrtc

let peer = webrtc.newPeer({
    iceServers: ["stun:stun.l.google.com:19302"],
})

webrtc.onConnectionStateChange(peer, fn(state) {
    println("state: " + state)
})

let chan = webrtc.addDataChannel(peer, "chat", fn(msg) {
    println("got: " + msg)
})

let offer = webrtc.createOffer(peer)
// exchange the offer/answer SDP with the remote peer via your signaling channel
```