gserver.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. require 'gserver'
  2. module Woe
  3. class Client
  4. attr_reader :id
  5. attr_reader :io
  6. def initialize(server, id, io)
  7. @server = server
  8. @id = id
  9. @io = io
  10. @busy = true
  11. end
  12. def on_input(line)
  13. # If the user says 'quit', disconnect them
  14. if line =~ /^\/quit/
  15. @busy = false
  16. # Shut down the server if we hear 'shutdown'
  17. elsif line =~ /^\/shutdown/
  18. @server.stop
  19. else
  20. @server.broadcast("Client #{id} says #{line}")
  21. end
  22. end
  23. def serve_once
  24. if IO.select([io], nil, nil, 0)
  25. # If so, retrieve the data and process it..
  26. line = io.gets
  27. on_input(line)
  28. else
  29. end
  30. end
  31. def serve
  32. while @busy
  33. serve_once
  34. end
  35. end
  36. end
  37. class Server < GServer
  38. def initialize(*args)
  39. super(*args)
  40. self.audit = true
  41. # increase the connection limit
  42. @maxConnections = 400
  43. # Keep an overall record of the client IDs allocated
  44. # and the lines of chat
  45. @client_id = 0
  46. @clients = []
  47. end
  48. def serve(io)
  49. # Increment the client ID so each client gets a unique ID
  50. @client_id += 1
  51. client = Client.new(self, @client_id, io)
  52. @clients << client
  53. client.io.puts("Welcome, client nr #{client.id}!")
  54. client.serve
  55. end
  56. def broadcast(msg)
  57. p msg
  58. @clients.each do |client|
  59. client.io.puts(msg)
  60. end
  61. end
  62. def self.run(port=7000)
  63. server = Woe::Server.new(port)
  64. server.start
  65. server.join
  66. end
  67. end
  68. end
  69. Woe::Server.run