kemal/docs/websockets.md

37 lines
830 B
Markdown
Raw Normal View History

2015-12-16 18:19:30 +00:00
# Using Websockets
Using Websockets is super easy! By nature Websockets are a bit different than standard Http Request/Response lifecycle.
You can easily create a websocket handler which matches the route of `ws://host:port/route. You can create more than 1 websocket handler
with different routes.
```ruby
2015-12-16 18:21:17 +00:00
ws "/" do |socket|
2015-12-16 18:19:30 +00:00
2015-12-16 18:21:17 +00:00
end
2015-12-16 18:19:30 +00:00
2015-12-16 18:21:17 +00:00
ws "/route2" do |socket|
2015-12-16 18:19:30 +00:00
2015-12-16 18:21:17 +00:00
end
2015-12-16 18:19:30 +00:00
```
Let's access the socket and create a simple echo server.
```ruby
2015-12-16 18:21:17 +00:00
# Matches "/"
ws "/" do |socket|
# Send welcome message to the client
socket.send "Hello from Kemal!"
# Handle incoming message and echo back to the client
socket.on_message do |message|
socket.send "Echo back from server #{message}"
end
# Executes when the client is disconnected. You can do the cleaning up here.
socket.on_close do
puts "Closing socket"
2015-12-16 18:19:30 +00:00
end
2015-12-16 18:21:17 +00:00
end
2015-12-16 18:19:30 +00:00
```