Crystal中Kemal Web框架的kemal-session模块的文档提供了这个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
我正在使用凯末尔Websocket。我有一个类似于以下示例的代码。如果我无法访问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
答案 0 :(得分:2)
Websocket连接也会产生上下文。您只需要从块中访问它,如
ws "/" do |socket, env|
env.session.int?("hello")
end