Guest User

Untitled

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