class Zashoku::Net::Server

Attributes

clients[RW]
handler[RW]

Public Class Methods

new(port) click to toggle source
# File lib/core/net/server.rb, line 14
def initialize(port)
  @clients = []
  @client_queue = {}
  @semaphore = Mutex.new
  @handler = ->(message) {}
  @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

Public Instance Methods

event(e) click to toggle source
# File lib/core/net/server.rb, line 33
def event(e)
  clients.each do |client|
    client.c.puts JSON.generate(e)
  end
end
exit() click to toggle source
# File lib/core/net/server.rb, line 29
def exit
  @server_thread.exit
end
handle(client) click to toggle source
# File lib/core/net/server.rb, line 39
def handle(client)
  expecting_helo = true
  loop do
    message =
      begin
        JSON.parse(client.c.readline.chomp)
      rescue EOFError
        { 'msg' => 'disconnect' }
      end
    if expecting_helo and message['msg'] != 'helo'
      Zashoku.logger.warn("#{client} did not say helo, rude!")
    end
    expecting_helo = false
    begin
      response = @handler.call(message)
      Zashoku.logger.debug("sending message to #{client}")
      if message['raw']
        #client.c.puts response.stat.size.to_s + Zashoku::EOF
        client.c.puts(response.gets(Zashoku::CConf[:core][:net][:bsize])) until response.eof?
        client.c.puts Zashoku::EOF
      else
        client.c.puts(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!() click to toggle source
# 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