Guest User

Untitled

a guest
Jan 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. require 'socket'
  2.  
  3. class SelectChatServer < TCPServer
  4.  
  5. def initialize(host,port)
  6. super host, port
  7. @sockets = [self]
  8. end
  9.  
  10. def start
  11. while(1)
  12. rs,ws,es = IO.select(@sockets,[], @sockets)
  13.  
  14. rs.each do | read_socket |
  15. # if it's the server, accept the connection
  16. # and add the socket to the list of clients to except
  17. if read_socket == self
  18. $stdout.puts "Got client"
  19. client = self.accept
  20. # Here we use module extension to add custom
  21. # properties and methods to a socket!
  22. client.extend(ChatClient)
  23. client.username = 'test'
  24. @sockets << client
  25. # need to throw out dead sockets
  26. elsif read_socket.closed? or read_socket.eof?
  27. # kill the whole thing if it's the server
  28. exit if read_socket == self
  29. $stdout.puts "Client closed connection"
  30. # remove the socket from the connected sockets list
  31. @sockets.reject! { |socket| socket == read_socket }
  32. else
  33. $stdout.puts "Got client data"
  34. data = read_socket.readline
  35. $stdout.puts data
  36. # write the data to all the other sockets except the server listener socket
  37. # and the author socket
  38. @sockets.map { | socket | socket.puts data unless socket == read_socket or item == self }
  39. end
  40. end
  41.  
  42. # throw out any sockets with errors
  43. es.each do | err_socket |
  44. $stderr.puts "Client error"
  45. @sockets.reject! { |socket| socket == err_socket }
  46. end
  47.  
  48. end
  49. end
  50.  
  51. end
  52.  
  53. # an example of a module to provide a custom
  54. # username property to a socket
  55. module ChatClient
  56. attr_accessor :username
  57. end
  58.  
  59. server = SelectChatServer.new("localhost", 3829)
  60. server.start
Add Comment
Please, Sign In to add comment