Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Kemal-sessions with websocket

The documentation for the kemal-session module for the Kemal web framework in Crystal provides this example:

require "kemal"
require "kemal-session"

get "/set" do |env|
  env.session.int("number", rand(100)) # set the value of "number"
  "Random number set."
end

get "/get" do |env|
  num  = env.session.int("number") # get the value of "number"
  env.session.int?("hello") # get value or nil, like []?
  "Value of random number is #{num}."
end

Kemal.run

I'm using Kemal with Websocket. I have a code similar to the following example. How can I uses sessions given that I don't have acces to env?

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"
  end
end
like image 234
Clement J. Avatar asked Dec 05 '25 10:12

Clement J.


1 Answers

Websocket connections also yields the context. You just need to access it from the block like

ws "/" do |socket, env|
  env.session.int?("hello")
end
like image 181
Serdar Dogruyol Avatar answered Dec 07 '25 17:12

Serdar Dogruyol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!