main.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. p "Hi from main.rb"
  2. p global_variables
  3. # p :$--TEST--
  4. # p $"--TEST
  5. log "hello to log"
  6. class Client
  7. attr_reader :id
  8. attr_reader :buffer
  9. attr_reader :in_lines
  10. def initialize(id)
  11. @id = id
  12. @buffer = ""
  13. @in_lines = []
  14. end
  15. def self.add(client_id)
  16. @clients ||= {}
  17. @clients[client_id] = Client.new(client_id)
  18. end
  19. def self.get(client_id)
  20. @clients ||= {}
  21. return @clients[client_id]
  22. end
  23. def self.remove(client_id)
  24. @clients[client_id] = nil
  25. end
  26. def send(text)
  27. log "Client #{@id}, send #{text}"
  28. Woe::Server.send_to_client(@id, text)
  29. end
  30. def on_input(str)
  31. @buffer ||= ""
  32. @buffer << str
  33. if @buffer["\r\n"]
  34. command, rest = @buffer.split("\r\n", 1)
  35. log "Client #{@id}, command #{command}"
  36. if (command.strip == "quit")
  37. self.send("Bye bye!")
  38. Woe::Server.disconnect(@id)
  39. Client.remove(@id)
  40. return nil
  41. else
  42. self.send("I don't know how to #{command}")
  43. end
  44. @buffer = rest
  45. end
  46. end
  47. end
  48. def woe_on_connect(client_id)
  49. p "Client #{client_id} connected"
  50. Client.add(client_id)
  51. end
  52. def woe_on_disconnect(client_id)
  53. p "Client #{client_id} disconnected"
  54. Client.remove(client_id)
  55. end
  56. def woe_on_input(client_id, buf)
  57. p "Client #{client_id} input #{buf}"
  58. client = Client.get(client_id)
  59. unless client
  60. log "Unknown client #{client_id} in woe_on_input."
  61. Woe::Server.disconnect(client_id)
  62. else
  63. p "Client #{client} #{client.id} ok."
  64. client.on_input(buf)
  65. end
  66. end
  67. def woe_on_signal(signal)
  68. log "Received signal in script #{signal}"
  69. if signal !=28
  70. Woe::Server.quit
  71. end
  72. end