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
24
# File 'lib/listen/tcp/broadcaster.rb', line 17

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

Instance Method Details

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



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

def _log(type, message)
  Celluloid::Logger.send(type, message)
end

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



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

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



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

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

#finalizeObject

Cleans up sockets and server



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

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

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

#runObject

Continuously accept and handle incoming connections



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

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



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

def start
  async.run
end