Class: Listen::TCP::Broadcaster
- Inherits:
-
Object
- Object
- Listen::TCP::Broadcaster
- Includes:
- Celluloid::IO
- Defined in:
- lib/listen/tcp/broadcaster.rb
Instance Attribute Summary collapse
-
#server ⇒ Object
readonly
Returns the value of attribute server.
-
#sockets ⇒ Object
readonly
Returns the value of attribute sockets.
Instance Method Summary collapse
-
#broadcast(payload) ⇒ Object
Broadcasts given payload to all connected sockets.
-
#finalize ⇒ Object
Cleans up sockets and server.
-
#handle_connection(socket) ⇒ Object
Handles incoming socket connection.
-
#initialize(host, port) ⇒ Broadcaster
constructor
Initializes a Celluloid::IO-powered TCP-broadcaster.
-
#run ⇒ Object
Continuously accept and handle incoming connections.
-
#start ⇒ Object
Asynchronously start accepting connections.
-
#unicast(socket, payload) ⇒ Boolean
Unicasts payload to given socket.
Constructor Details
#initialize(host, port) ⇒ Broadcaster
Initializes a Celluloid::IO-powered TCP-broadcaster
Note: Listens on all addresses when host is nil
19 20 21 22 |
# File 'lib/listen/tcp/broadcaster.rb', line 19 def initialize(host, port) @server = TCPServer.new(host, port) @sockets = [] end |
Instance Attribute Details
#server ⇒ Object (readonly)
Returns the value of attribute server.
10 11 12 |
# File 'lib/listen/tcp/broadcaster.rb', line 10 def server @server end |
#sockets ⇒ Object (readonly)
Returns the value of attribute sockets.
10 11 12 |
# File 'lib/listen/tcp/broadcaster.rb', line 10 def sockets @sockets end |
Instance Method Details
#broadcast(payload) ⇒ Object
Broadcasts given payload to all connected sockets
39 40 41 42 43 |
# File 'lib/listen/tcp/broadcaster.rb', line 39 def broadcast(payload) @sockets.each do |socket| unicast(socket, payload) end end |
#finalize ⇒ Object
Cleans up sockets and server
30 31 32 33 34 35 36 |
# File 'lib/listen/tcp/broadcaster.rb', line 30 def finalize if @server @sockets.clear @server.close @server = nil end end |
#handle_connection(socket) ⇒ Object
Handles incoming socket connection
65 66 67 |
# File 'lib/listen/tcp/broadcaster.rb', line 65 def handle_connection(socket) @sockets << socket end |
#run ⇒ Object
Continuously accept and handle incoming connections
58 59 60 61 62 |
# File 'lib/listen/tcp/broadcaster.rb', line 58 def run while socket = @server.accept handle_connection(socket) end end |
#start ⇒ Object
Asynchronously start accepting connections
25 26 27 |
# File 'lib/listen/tcp/broadcaster.rb', line 25 def start async.run end |
#unicast(socket, payload) ⇒ Boolean
Unicasts payload to given socket
49 50 51 52 53 54 55 |
# File 'lib/listen/tcp/broadcaster.rb', line 49 def unicast(socket, payload) socket.write(payload) true rescue IOError, Errno::ECONNRESET, Errno::EPIPE @sockets.delete(socket) false end |