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.

Summary

Functions

Callback implementation for Plug.call/2.

Link to this function

handle_event(event, conn)

View Source

Callback implementation for Plug.init/1.

Link to this function

websocket_handle(arg, req, opts)

View Source
Link to this function

websocket_init(transport_name, req, opts)

View Source
Link to this function

websocket_terminate(reason, req, opts)

View Source