Class: Mata::Broadcaster
- Inherits:
-
Object
- Object
- Mata::Broadcaster
- Defined in:
- lib/mata/broadcaster.rb
Instance Method Summary collapse
- #broadcast_to_all(files) ⇒ Object
- #deliver_payload ⇒ Object
- #establish_contact(env) ⇒ Object
-
#initialize ⇒ Broadcaster
constructor
A new instance of Broadcaster.
- #stand_down ⇒ Object
Constructor Details
#initialize ⇒ Broadcaster
Returns a new instance of Broadcaster.
5 6 7 8 9 |
# File 'lib/mata/broadcaster.rb', line 5 def initialize @clients = [] @clients_mutex = Mutex.new @cleanup_thread = cleanup_periodically end |
Instance Method Details
#broadcast_to_all(files) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/mata/broadcaster.rb', line 45 def broadcast_to_all(files) clients_copy = @clients_mutex.synchronize { @clients.dup } return if clients_copy.empty? files.each do |file| event_data = {type: "reload"} = "data: #{event_data.to_json}\n\n" clients_copy.each do |stream| stream << rescue @clients_mutex.synchronize { @clients.delete(stream) } end end end |
#deliver_payload ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/mata/broadcaster.rb', line 36 def deliver_payload idiomorph_js = File.read(File.join(__dir__, "idiomorph.min.js")) client_js = File.read(File.join(__dir__, "client.js")) script = "#{idiomorph_js}\n\n#{client_js}" [200, {"content-type" => "application/javascript"}, [script]] end |
#establish_contact(env) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/mata/broadcaster.rb', line 11 def establish_contact(env) if env["REQUEST_METHOD"] != "GET" return [405, {}, []] end headers = { "content-type" => "text/event-stream", "cache-control" => "no-cache", "connection" => "keep-alive", "access-control-allow-origin" => "*" } [200, headers, proc { |stream| @clients_mutex.synchronize do @clients << stream end begin stream << "data: {\"type\":\"connected\"}\n\n" rescue @clients_mutex.synchronize { @clients.delete(stream) } end }] end |
#stand_down ⇒ Object
61 62 63 64 65 |
# File 'lib/mata/broadcaster.rb', line 61 def stand_down @cleanup_thread&.kill @clients_mutex.synchronize { @clients.clear } end |