ChannelSocket
ChannelSocket module: WebSocket transport adapter for Channels.
ChannelSocket integrates the Channel wire protocol with March's WebSocket server. A socket endpoint is mounted in the HTTP router and handles:
- WebSocket upgrade for incoming connections.
- Authentication via the user-supplied connect/2 callback.
- Routing incoming phx_join messages to the correct channel handler.
- Forwarding ChannelPush messages from channel processes to the wire.
Usage:
fn my_router() do HttpServer.new(4000) |> HttpServer.plug(ChannelSocket.handler("/socket", my_routes, connect_fn)) |> HttpServer.listen() end
fn connect_fn(params, socket) do match verify_token(params) do | Ok(user) -> Ok(Channel.assign(socket, "user", user)) | Err(_) -> Err("unauthorized") end end
Socket route list: Each ChannelRoute maps a topic pattern to a handler name string. On join, the handler name is used to look up the handler functions in the environment (see ChannelServer for the handler function protocol).
Transport loop (per client connection): The WebSocket handler runs a loop reading frames from the wire, deserialising them as ChannelMsg, and dispatching to channel processes. Outbound ChannelPush messages from channel processes are serialised and sent back over the WebSocket.
See also: channel.march, channel_server.march, websocket.march.
Types
Functions
Construct a SocketConfig.
Construct a SocketConfig with pre-started shard pids.
Return the path of a SocketConfig.
Return the routes of a SocketConfig.
Return the shard pids of a SocketConfig.
Find the first ChannelRoute whose pattern matches topic. Returns Some(route) if found, None otherwise.
True when any route in routes matches topic.
Empty active channels map.
Register a channel process pid for a topic.
Look up the channel process pid for a topic.
Remove a channel from the registry (after leave).
Return all (topic, pid) pairs in the active channels map.
Route a parsed ChannelMsg to the appropriate channel process or handle it as a socket-level message (phx_join, phx_leave, phx_heartbeat). Returns an updated ActiveChannels or triggers side effects. Requires actor runtime.
Parse a WebSocket TextFrame string as a ChannelMsg. Returns Some(msg) or None on parse failure.
Serialize a ChannelMsg for sending as a WebSocket TextFrame.
Build a Conn → Conn plug function that handles WebSocket upgrade for the socket path. Mount with HttpServer.plug/2.
The plug:
- Checks that the request path starts with
socket_path. - Upgrades to WebSocket.
- In the WS handler loop: reads frames, parses them as ChannelMsgs,
and routes them.
Usage: HttpServer.new(4000) |> HttpServer.plug(ChannelSocket.plug_for(cfg)) |> HttpServer.listen()