lattice
Lattice
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.
Installation
-
Add the dependency to your
shard.yml
:dependencies: lattice: github: rubyattack3r/lattice
-
Run
shards install
Usage
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
While Lattice provides everything needed for basic WebSocket functionality, you can extend ClientSocket
to include your 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
Contributing
- Fork it (https://github.com/rubyattack3r/lattice/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- rubyattack3r - creator and maintainer
Repository
lattice
Owner
Statistic
- 0
- 0
- 0
- 0
- 1
- 10 days ago
- January 7, 2025
License
MIT License
Links
Synced at
Fri, 17 Jan 2025 09:24:38 GMT
Languages