Class: Zashoku::Net::Server
- Inherits:
-
Object
- Object
- Zashoku::Net::Server
- Defined in:
- lib/core/net/server.rb
Instance Attribute Summary collapse
-
#clients ⇒ Object
Returns the value of attribute clients.
-
#handler ⇒ Object
Returns the value of attribute handler.
Instance Method Summary collapse
- #event(e) ⇒ Object
- #exit ⇒ Object
- #handle(client) ⇒ Object
-
#initialize(port) ⇒ Server
constructor
A new instance of Server.
- #serve_clients! ⇒ Object
Constructor Details
#initialize(port) ⇒ Server
Returns a new instance of Server.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/core/net/server.rb', line 14 def initialize(port) @clients = [] @client_queue = {} @semaphore = Mutex.new @handler = ->() {} @server = begin TCPServer.new(port) rescue Errno::EADDRINUSE raise "error, port #{port} is busy" end @server_thread = Thread.new { serve_clients! } Zashoku.logger.info("serving customers on localhost:#{port}") end |
Instance Attribute Details
#clients ⇒ Object
Returns the value of attribute clients.
12 13 14 |
# File 'lib/core/net/server.rb', line 12 def clients @clients end |
#handler ⇒ Object
Returns the value of attribute handler.
12 13 14 |
# File 'lib/core/net/server.rb', line 12 def handler @handler end |
Instance Method Details
#event(e) ⇒ Object
33 34 35 36 37 |
# File 'lib/core/net/server.rb', line 33 def event(e) clients.each do |client| client.c.puts JSON.generate(e) end end |
#exit ⇒ Object
29 30 31 |
# File 'lib/core/net/server.rb', line 29 def exit @server_thread.exit end |
#handle(client) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/core/net/server.rb', line 39 def handle(client) expecting_helo = true loop do = begin JSON.parse(client.c.readline.chomp) rescue EOFError { 'msg' => 'disconnect' } end if expecting_helo and ['msg'] != 'helo' Zashoku.logger.warn("#{client} did not say helo, rude!") end expecting_helo = false begin response = @handler.call() Zashoku.logger.debug("sending message to #{client}") client.c.puts( if ['raw'] response.length.to_s + Zashoku::EOF + response + Zashoku::EOF else JSON.generate(response: response) end ) rescue Errno::EPIPE break else break unless response end end Zashoku.logger.info("bye bye #{client}") @clients.delete(client) @client_queue.delete(client) client.c.close end |
#serve_clients! ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/core/net/server.rb', line 74 def serve_clients! Thread.abort_on_exception = true loop do Thread.start(@server.accept) do |client| csan = ClientSan.new(client) Zashoku.logger.info("#{csan} connected") @clients << csan @client_queue[csan] = Queue.new handle(csan) end end end |