client.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Model and handle the clients of the server
  2. class Client
  3. attr_reader :id
  4. attr_reader :buffer
  5. attr_reader :in_lines
  6. def initialize(id)
  7. @id = id
  8. @buffer = ""
  9. @in_lines = []
  10. end
  11. def self.add(client_id)
  12. @clients ||= {}
  13. @clients[client_id] = Client.new(client_id)
  14. end
  15. def self.get(client_id)
  16. @clients ||= {}
  17. return @clients[client_id]
  18. end
  19. def self.remove(client_id)
  20. @clients[client_id] = nil
  21. end
  22. def send(text)
  23. log "Client #{@id}, send #{text}"
  24. Woe::Server.send_to_client(@id, text)
  25. end
  26. def puts(text)
  27. log "Client #{@id}, puts #{text}"
  28. Woe::Server.puts(@id, text)
  29. end
  30. def printf(fmt, *args)
  31. text = fmt.format(*args)
  32. puts(text)
  33. end
  34. def raw_puts(text)
  35. log "Client #{@id}, puts #{text}"
  36. Woe::Server.raw_puts(@id, text)
  37. end
  38. def raw_printf(fmt, *args)
  39. text = fmt.format(*args)
  40. puts(text)
  41. end
  42. def on_input(str)
  43. @buffer ||= ""
  44. @buffer << str
  45. if @buffer["\r\n"]
  46. command, rest = @buffer.split("\r\n", 1)
  47. log "Client #{@id}, command #{command}"
  48. if (command.strip == "quit")
  49. self.send("Bye bye!")
  50. Woe::Server.disconnect(@id)
  51. Client.remove(@id)
  52. return nil
  53. else
  54. self.send("I don't know how to #{command}")
  55. end
  56. @buffer = rest
  57. end
  58. end
  59. end
  60. log "Mruby client script loaded OK."