Search code examples
websocketkemal

Send data to a decent user with Kemal over websocket


How can i send data data to a decent user connected via websockets? I know, Websocket connections yields the context, but how can i filter a decent socket connection for sending data to only 1 (or some) connected user(s) depending on context (env)?

SOCKETS = [] of HTTP::WebSocket
ws "/chat" do |socket,env|
  room = env.params.query["room"]
  SOCKETS << socket
  socket.on_message do |message|
    SOCKETS.each { |socket| socket.send message}
  end
  socket.on_close do
    SOCKETS.delete socket
  end
end

Must socket contain the room or needs SOCKETS to be a Hash?


Solution

  • You can store sockets as hash and give id to your clients and then you can send saved socket of your recent client.

    I mean that

    SOCKETS = {} of String => HTTP::WebSocket
    
    socket.on_message do |message|
      j = JSON.parse(message)
      case j["type"]
      when "login"
        user_id = j["id"].to_s
        SOCKETS[user_id] = socket
      when "whisper"
        to = j["to"].to_s
        from = j["from"]
        user = SOCKETS[to].send("#{from} is whispering you!")
    end
    

    something like that.