Nex.WebSocket
(nex_core v0.4.3)
Copy Markdown
User-level WebSocket support for Nex applications.
Provides bidirectional real-time communication via WebSocket connections.
Built on top of WebSockAdapter (already a framework dependency).
Usage
Define a WebSocket handler in src/api/ using Nex.WebSocket:
defmodule MyApp.Api.Chat do
use Nex.WebSocket
def handle_connect(state) do
{:ok, state}
end
def handle_message("ping", state) do
{:reply, "pong", state}
end
def handle_message(msg, state) do
{:reply, "echo: " <> msg, state}
end
def handle_disconnect(state) do
{:ok, state}
end
endThe module is automatically routed to /ws/chat (mirrors the API path convention).
Connect from the browser:
const ws = new WebSocket("ws://localhost:4000/ws/chat");
ws.onmessage = (e) => console.log(e.data);
ws.send("ping");Callbacks
handle_connect/1— called when a client connects. Return{:ok, state}.handle_message/2— called for each incoming message. Return:{:reply, message, state}— send a message back to the client{:ok, state}— no reply{:stop, reason, state}— close the connection
handle_disconnect/1— called when the client disconnects. Return{:ok, state}.
Initial State
Override initial_state/1 to set per-connection state from the request:
def initial_state(req) do
%{user_id: Nex.Session.get(:user_id), joined_at: DateTime.utc_now()}
endBroadcasting
Use Nex.WebSocket.broadcast/2 to send messages to all connected clients
on a named topic (requires Phoenix.PubSub, already a framework dependency):
Nex.WebSocket.broadcast("chat", "New message!")Subscribe in handle_connect/1:
def handle_connect(state) do
Nex.WebSocket.subscribe("chat")
{:ok, state}
end
Summary
Functions
Broadcasts a message to all subscribers on the given topic.
Subscribes the current WebSocket process to a topic.
Call from within handle_connect/1.