Class: Listen::TCP::Broadcaster

Inherits:
Object
  • Object
show all
Includes:
Celluloid::IO
Defined in:
lib/listen/tcp/broadcaster.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Broadcaster

Initializes a Celluloid::IO-powered TCP-broadcaster

Note: Listens on all addresses when host is nil

Parameters:

  • host (String)

    to broadcast on

  • port (String)

    to broadcast on



17
18
19
20
21
22
23
# File 'lib/listen/tcp/broadcaster.rb', line 17

def initialize(host, port)
  @sockets = []
  @server = TCPServer.new(host, port)
rescue
  _log :error, "Broadcaster.initialize: #{$!.inspect}:#{$@.join("\n")}"
  raise
end

Instance Method Details

#_log(type, message) ⇒ Object (private)



62
63
64
# File 'lib/listen/tcp/broadcaster.rb', line 62

def _log(type, message)
  Celluloid.logger.send(type, message)
end

#_unicast(socket, payload) ⇒ Object (private)



66
67
68
69
70
71
72
# File 'lib/listen/tcp/broadcaster.rb', line 66

def _unicast(socket, payload)
  socket.write(payload)
  true
rescue IOError, Errno::ECONNRESET, Errno::EPIPE
  _log :debug, "Broadcaster failed: #{socket.inspect}"
  false
end

#broadcast(payload) ⇒ Object

Broadcasts given payload to all connected sockets



41
42
43
44
45
46
# File 'lib/listen/tcp/broadcaster.rb', line 41

def broadcast(payload)
  active_sockets = @sockets.select do |socket|
    _unicast(socket, payload)
  end
  @sockets.replace(active_sockets)
end

#finalizeObject

Cleans up sockets and server



31
32
33
34
35
36
37
38
# File 'lib/listen/tcp/broadcaster.rb', line 31

def finalize
  @sockets.map(&:close) if @sockets
  @sockets = nil

  return unless @server
  @server.close
  @server = nil
end

#runObject

Continuously accept and handle incoming connections



49
50
51
52
53
54
55
56
57
58
# File 'lib/listen/tcp/broadcaster.rb', line 49

def run
  while socket = @server.accept
    @sockets << socket
  end
rescue Celluloid::Task::TerminatedError
  _log :debug, "TCP adapter was terminated: #{$!.inspect}"
rescue
  _log :error, "Broadcaster.run: #{$!.inspect}:#{$@.join("\n")}"
  raise
end

#startObject

Asynchronously start accepting connections



26
27
28
# File 'lib/listen/tcp/broadcaster.rb', line 26

def start
  async.run
end