Class: ADAM6050::Server
- Inherits:
-
Object
- Object
- ADAM6050::Server
- Defined in:
- lib/adam6050/server.rb
Overview
The server listens to a speciefied UDP port and delegates incomming messages to the different handlers.
Constant Summary collapse
- DEFAULT_PORT =
Returns the dafault port of the UDP server.
1025
Instance Attribute Summary collapse
-
#logger ⇒ Logger
readonly
The logger used by the server.
-
#state ⇒ Integer
readonly
The current state.
Instance Method Summary collapse
-
#initialize(password: nil, logger: Logger.new(STDOUT)) ⇒ Server
constructor
A new instance of Server.
-
#run(host: nil, port: DEFAULT_PORT) {|Integer| ... } ⇒ nil
Starts a new UDP server that listens on the given port.
-
#update {|Integer| ... } ⇒ Object
Updates the state atomicly.
Constructor Details
#initialize(password: nil, logger: Logger.new(STDOUT)) ⇒ Server
Returns a new instance of Server.
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/adam6050/server.rb', line 19 def initialize(password: nil, logger: Logger.new(STDOUT)) @session = Session.new @handlers = [ Handler::Login.new(password), Handler::Status.new, Handler::Read.new, Handler::Write.new ] @state = State.initial @state_lock = Mutex.new @logger = logger end |
Instance Attribute Details
#logger ⇒ Logger (readonly)
Returns the logger used by the server.
11 12 13 |
# File 'lib/adam6050/server.rb', line 11 def logger @logger end |
#state ⇒ Integer (readonly)
Returns the current state.
14 15 16 |
# File 'lib/adam6050/server.rb', line 14 def state @state end |
Instance Method Details
#run(host: nil, port: DEFAULT_PORT) {|Integer| ... } ⇒ nil
Starts a new UDP server that listens on the given port. The state is updated atomically and yielded to an optional block everytime a change is made. By returning ‘false` the block can cancel the state update. This call is blocking.
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/adam6050/server.rb', line 43 def run(host: nil, port: DEFAULT_PORT, &block) logger.info "Listening on port #{port}" Socket.udp_server_loop host, port do |msg, sender| logger.debug { "#{sender.remote_address.inspect} -> '#{msg.inspect}'" } handler = @handlers.find { |h| h.handles? msg } || next @state_lock.synchronize do handle(handler, msg, sender, &block) end end nil end |
#update {|Integer| ... } ⇒ Object
Updates the state atomicly. The current state will be yielded to the given block and the return value used as the next state.
60 61 62 63 64 |
# File 'lib/adam6050/server.rb', line 60 def update @state_lock.synchronize do @state = yield @state end end |