View Source Websocket.Handler (websocket_handler v0.0.1)
Websocket.Handler provides a macro-based approach to handle WebSocket connections in a Plug-based application.
This module also serves the JavaScript WebSocket client code at the /ws/client.js
endpoint.
Usage
To use Websocket.Handler, you need to include it in your application’s router module and define event handlers using the provided macros.
defmodule MyWebsocketRouter do
use Websocket.Handler
on(:connect) do
IO.puts("Client connected")
end
on(:disconnect) do
IO.puts("Client disconnected")
end
on(:json) do
IO.puts("Received JSON: #{inspect(conn.json)}")
end
on(:file) do
# Save the file to disk or process it
IO.puts("Received file")
end
on(:message) do
IO.puts("Received message: #{conn.message}")
end
end
Routes
get "/client.js"
: Serves the JavaScript WebSocket client at the/ws/client.js
endpoint.forward "/ws"
: Reserved for WebSocket connections. Forwards WebSocket requests to the module where event handlers are defined.
Macros
on(event, do: block)
: Defines a callback for a specific WebSocket event. Supported events include::connect
: Triggered when a client connects.:disconnect
: Triggered when a client disconnects.:json
: Triggered when a JSON message is received.:file
: Triggered when binary data (file) is received.:message
: Triggered when a plain text message is received.