If you only need to push UI updates to the client, check out Auto Refresh - a higher-level API built on WebSockets.
Creating a WebSocket Controller
Your WebSocket is now accessible at
ws://localhost:8000/HelloWorldController.
Connecting from JavaScript
Instatic/app.js:
Sending and Receiving Messages
Server-Side
Receive data from the client:receiveData blocks until the client sends data.
Client-Side
Send data to the server:Working with JSON
Send JSON from the server:{"name":"Alice"}
Receiving Different Data Types
Managing State
Define states in your controller type:The connection closes automatically when
run completes. Use forever to keep it open:Accessing the Current User
Use normal auth functions in WebSocket controllers:Advanced Features
Custom Routing
Use a custom path:/my-ws.
Custom Data Types
ImplementWebSocketsData for custom decoders:
Ping Handling
By default, the server pings every 30 seconds. OverrideonPing to run custom code:
Lifecycle Events
initialState- Initial controller staterun- Main WebSocket logiconClose- Called when connection closesonPing- Called after each ping (every 30 seconds)
State Management Functions
getState- Retrieve current statesetState- Update state