Guest User

Untitled

a guest
Apr 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. require 'gserver'
  2.  
  3. $ApplicationPort = 9319
  4.  
  5. class ChatServer < GServer
  6. def initialize(port, *args)
  7. super(port, *args)
  8.  
  9. # Keep an overall record of the client IDs allocated
  10. # and the lines of chat
  11. @@client_id = 0
  12. @@chat = []
  13. puts 'Server up running'
  14. end
  15.  
  16. def serve(io)
  17. # Increment the client ID so each client gets a unique ID
  18. @@client_id += 1
  19. my_client_id = @@client_id
  20. my_position = @@chat.size
  21.  
  22. io.puts("Welcome to the chat, client #{@@client_id}!")
  23. puts("To [#{@@client_id}]: Welcome to the chat, client #{@@client_id}!")
  24.  
  25. # Leave a message on the chat queue to signify this client
  26. # has joined the chat
  27. @@chat << [my_client_id, ""]
  28.  
  29. loop do
  30. # Every 5 seconds check to see if we are receiving any data
  31. if IO.select([io], nil, nil, 2)
  32. # If so, retrieve the data and process it..
  33. line = io.gets
  34. puts "From [#{my_client_id}]: "+line
  35.  
  36. # If the user says 'quit', disconnect them
  37. if line =~ /quit/
  38. @@chat << [my_client_id, ""]
  39. break
  40. end
  41.  
  42. # Shut down the server if we hear 'shutdown'
  43. self.stop if line =~ /shutdown/
  44.  
  45. # Add the client's text to the chat array along with the
  46. # client's ID
  47. @@chat << [my_client_id, line]
  48. else
  49. # No data, so print any new lines from the chat stream
  50. @@chat[my_position..-1].each_with_index do |line, index|
  51. io.puts("#{line[0]} says: #{line[1]}")
  52. end
  53.  
  54. # Move the position to one past the end of the array
  55. my_position = @@chat.size
  56. end
  57. end
  58.  
  59. end
  60. end
  61.  
  62. server = ChatServer.new($ApplicationPort)
  63. server.audit = true
  64. server.start
  65.  
  66. loop do
  67. break if server.stopped?
  68. end
  69.  
  70. puts "Server has been terminated"
Add Comment
Please, Sign In to add comment