Class: Listen::TCP::Broadcaster

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

Instance Attribute Summary collapse

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



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

#serverObject (readonly)

Returns the value of attribute server.



10
11
12
# File 'lib/listen/tcp/broadcaster.rb', line 10

def server
  @server
end

#socketsObject (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

#finalizeObject

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

#runObject

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

#startObject

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

Returns:

  • (Boolean)

    whether writing to socket was succesful



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