module Lattice
Overview
A lightweight, standalone WebSocket framework for Crystal, derived from Amber's WebSocket implementation. Lattice provides a clean, efficient way to handle real-time communication without the overhead of session management or complex adapters.
Defining a Socket
struct UserSocket < Lattice::ClientSocket
channel "user_room:*", UserChannel
def on_connect
# Add authentication logic here
true
end
end
Creating a Channel
class ChatChannel < Lattice::Channel
def handle_joined(client_socket)
# Handle user joining chat
end
def handle_message(client_socket, message)
# Process and broadcast message
rebroadcast!(message)
end
def handle_leave(client_socket)
# Clean up when user leaves
end
end
Setting Up the Server
require "lattice"
# Initialize WebSocket handler
ws_handler = Lattice::Handler.new("/ws", "UserSocket") do |socket, context|
UserSocket.new(socket, context)
end
# Add to your HTTP server
server = HTTP::Server.new([
HTTP::LogHandler.new,
ws_handler,
])
server.listen(3000)
Custom Application Context
The ClientSocket
can be extended to include custom application context:
struct ExtendedUserSocket < Lattice::ClientSocket
channel "user_room:*", ClientServiceChannel
property application_context : ApplicationContext
def initialize(@socket : HTTP::WebSocket, @context : HTTP::Server::Context, @application_context : ApplicationContext)
super(@socket, @context)
end
def on_connect
@app.auth_service.valid_token?(context.request.headers["Authorization"]?)
end
end
# Initialize with context
application_context = ApplicationContext.new
ws_handler = Lattice::Handler.new("/ws", "ExtendedUserSocket") do |socket, context|
ExtendedUserSocket.new(socket, context, application_context).as(Lattice::ClientSocket)
end
Extended Modules
Defined in:
lattice.crlattice/channel.cr
lattice/client_socket.cr
lattice/client_sockets.cr
lattice/handler.cr
lattice/subscription_manager.cr
Constant Summary
-
Log =
::Log.for(self)
-
VERSION =
"0.1.0"
Class Method Summary
-
.topic_path(topic)
Helper method to get the path of a topic