class Client
Constants
- BIND_ADDR
- MULTICAST_ADDR
- PORT
Public Class Methods
new(handle)
click to toggle source
# File lib/backchannel/client.rb, line 11 def initialize(handle) @handle = handle @client_id = SecureRandom.hex(5) @listeners = [] end
Public Instance Methods
add_message_listener(listener)
click to toggle source
# File lib/backchannel/client.rb, line 17 def add_message_listener(listener) listen unless listening? @listeners << listener end
transmit(content)
click to toggle source
# File lib/backchannel/client.rb, line 22 def transmit(content) message = Message.new( "client_id" => @client_id, "handle" => @handle, "content" => content ) socket.send(message.to_json, 0, MULTICAST_ADDR, PORT) message end
Private Instance Methods
bind_address()
click to toggle source
# File lib/backchannel/client.rb, line 64 def bind_address IPAddr.new(MULTICAST_ADDR).hton + IPAddr.new(BIND_ADDR).hton end
listen()
click to toggle source
# File lib/backchannel/client.rb, line 35 def listen socket.bind(BIND_ADDR, PORT) Thread.new do loop do attributes, _ = socket.recvfrom(1024) message = Message.inflate(attributes) unless message.client_id == @client_id @listeners.each { |listener| listener.new_message(message) } end end end @listening = true end
listening?()
click to toggle source
# File lib/backchannel/client.rb, line 52 def listening? @listening == true end
socket()
click to toggle source
# File lib/backchannel/client.rb, line 56 def socket @socket ||= UDPSocket.open.tap do |socket| socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, bind_address) socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, 1) socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) end end