Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'socket'
- class SelectChatServer < TCPServer
- def initialize(host,port)
- super host, port
- @sockets = [self]
- end
- def start
- while(1)
- rs,ws,es = IO.select(@sockets,[], @sockets)
- rs.each do | read_socket |
- # if it's the server, accept the connection
- # and add the socket to the list of clients to except
- if read_socket == self
- $stdout.puts "Got client"
- client = self.accept
- # Here we use module extension to add custom
- # properties and methods to a socket!
- client.extend(ChatClient)
- client.username = 'test'
- @sockets << client
- # need to throw out dead sockets
- elsif read_socket.closed? or read_socket.eof?
- # kill the whole thing if it's the server
- exit if read_socket == self
- $stdout.puts "Client closed connection"
- # remove the socket from the connected sockets list
- @sockets.reject! { |socket| socket == read_socket }
- else
- $stdout.puts "Got client data"
- data = read_socket.readline
- $stdout.puts data
- # write the data to all the other sockets except the server listener socket
- # and the author socket
- @sockets.map { | socket | socket.puts data unless socket == read_socket or item == self }
- end
- end
- # throw out any sockets with errors
- es.each do | err_socket |
- $stderr.puts "Client error"
- @sockets.reject! { |socket| socket == err_socket }
- end
- end
- end
- end
- # an example of a module to provide a custom
- # username property to a socket
- module ChatClient
- attr_accessor :username
- end
- server = SelectChatServer.new("localhost", 3829)
- server.start
Add Comment
Please, Sign In to add comment