Created
May 20, 2016 23:30
-
-
Save whitehat101/29b55375b8d0d35f38f625c49421219d to your computer and use it in GitHub Desktop.
Simple WebSocket Channel Managment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
class SingleChannel | |
def initialize id | |
@id = id | |
@sockets = Set.new | |
end | |
def push ws | |
@sockets << ws | |
end | |
def delete ws | |
@sockets.delete ws | |
end | |
def send message, type = 'text' | |
@sockets.each { |ws| internal_send ws, message, type } | |
end | |
private | |
def internal_send ws, message, type | |
ws.send message, type: type | |
rescue => e | |
puts "Channel(#{@id}): removing ws:#{ws}\n error #{e}: #{e.message}" | |
delete ws | |
end | |
end | |
class FakeWS | |
def send msg, opts = {} | |
puts "FakeWS(#{opts}): #{msg}" | |
end | |
end | |
Channel = Hash.new { |hash, key| hash[key] = SingleChannel.new key } | |
Channel[1024].push FakeWS.new | |
Channel[1024].push FakeWS.new | |
Channel[1024].push FakeWS.new | |
Channel[1000].push FakeWS.new | |
Channel[42].push FakeWS.new | |
Channel[1024].send 'msg' | |
Channel[0].send 'msg' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment