Skip to content

Instantly share code, notes, and snippets.

@whitehat101
Created May 20, 2016 23:30
Show Gist options
  • Save whitehat101/29b55375b8d0d35f38f625c49421219d to your computer and use it in GitHub Desktop.
Save whitehat101/29b55375b8d0d35f38f625c49421219d to your computer and use it in GitHub Desktop.
Simple WebSocket Channel Managment
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