-
Notifications
You must be signed in to change notification settings - Fork 31
-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Separate Channels? #4
Comments
Can you provide some example code of how you would ideally like to be able to use separate channels? |
Right now every single socket connect is being stored in the array in settings.sockets. It would be nice to be able to group socket connects into different arrays so that a message will only be sent to other subscribers in that same array and the others would not get a message. Below is an example of a way I was trying to implement it, but I could not get it to work. class Connection
include DataMapper::Resource
property :id, Serial
property :socket, Object
property :channel, String
end
#set :sockets, []
get '/' do
if !request.websocket?
erb :index
else
request.websocket do |ws|
channel = params[:id]
@con = Connection.first_or_create(channel: channel, socket: ws)
ws.onopen do
ws.send("Hello World!")
#settings.sockets << ws
end
ws.onmessage do |msg|
@allconnections = Connection.all(channel: channel)
EM.next_tick { @allconnections.each{|s| s.socket.send(msg) } }
end
ws.onclose do
warn("wetbsocket closed")
@con.destroy
end
end
end
end |
This is what I ended up going with get '/socket/live/game/:id' do
if !request.websocket?
puts "Not a websocket request"
else
request.websocket do |ws|
channel = params[:id]
@con = {channel: channel, socket: ws}
ws.onopen do
ws.send("Hello World!")
settings.sockets << @con
end
ws.onmessage do |msg|
return_array = []
settings.sockets.each do |hash|
#puts hash
#puts hash['channel']
if hash[:channel] == channel
#puts hash[:socket]
return_array << hash
puts "Same channel"
puts return_array
else
puts hash[:channel]
puts channel
puts "Not in same channel"
end
end
EM.next_tick { return_array.each{|s| s[:socket].send(msg) } }
end
ws.onclose do
warn("websocket closed")
settings.sockets.each do |hash|
if hash[:socket] == ws
settings.sockets.delete(hash)
puts "deleted"
else
puts "not deleted"
end
end
end
end
end
end |
Hi, I really like using your implementation of websockets in Sinatra, but I have been having difficulty coming up with a way of creating separate websocket 'channels.' Is there an elegant way of doing so with this gem?
The text was updated successfully, but these errors were encountered: