GameServerWeb.WebRTCPeer (game_server_web v1.0.938)

Copy Markdown

Manages a server-side WebRTC PeerConnection for a single user.

This GenServer owns an ExWebRTC.PeerConnection process and acts as the bridge between the Phoenix Channel (signaling) and the WebRTC DataChannels for low-latency hook RPC calls.

Lifecycle

  1. Started by UserChannel when the client sends a "webrtc:offer" event.
  2. Linked to the channel process — auto-terminates when WebSocket disconnects.
  3. Handles SDP offer/answer exchange and ICE candidate relay.
  4. Processes hook RPC calls received on the "events" DataChannel.
  5. Provides send_data/3 to push hook responses back to the client.

Hook RPC

Clients send JSON messages on the "events" DataChannel:

{"type": "call_hook", "plugin": "my_plugin", "fn": "my_func", "args": [1, 2]}

The server replies on the same channel with:

{"type": "hook_reply", "plugin": "my_plugin", "fn": "my_func", "data": result}

Or on error:

{"type": "hook_error", "plugin": "my_plugin", "fn": "my_func", "error": "reason"}

Messages sent to the controlling channel process

  • {:webrtc_answer, answer_json} — SDP answer to send to client
  • {:webrtc_ice, candidate_json} — ICE candidate to send to client
  • {:webrtc_channel_open, ref, label} — DataChannel opened
  • {:webrtc_channel_closed, ref} — DataChannel closed
  • {:webrtc_connection_state, state} — connection state change

Summary

Functions

Adds a remote ICE candidate received from the client.

Returns a specification to start this module under a supervisor.

Closes the WebRTC peer connection and stops this process.

Returns the current connection state.

Handles an incoming SDP offer from the client. Sends {:webrtc_answer, answer_json} back to the controlling process.

Sends data to the client over a named DataChannel. Returns :ok or {:error, reason}.

Starts a WebRTCPeer linked to the calling process (typically a channel).

Functions

add_ice_candidate(pid, candidate_json)

Adds a remote ICE candidate received from the client.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

close(pid)

Closes the WebRTC peer connection and stops this process.

connection_state(pid)

Returns the current connection state.

handle_offer(pid, offer_json)

Handles an incoming SDP offer from the client. Sends {:webrtc_answer, answer_json} back to the controlling process.

send_data(pid, channel_label, data)

Sends data to the client over a named DataChannel. Returns :ok or {:error, reason}.

start_link(opts)

Starts a WebRTCPeer linked to the calling process (typically a channel).

Options

  • :user_id — the authenticated user's ID (required)
  • :ice_servers — list of ICE server configs (optional, defaults to config)