require 'gserver'

class ChatServer < GServer
  def initialize *args
    super

    
    @chatters = []

    
    @mutex = Mutex.new 
  end

  
  def broadcast message, sender = nil
    
    message = message.strip << 

    
    @mutex.synchronize do
      @chatters.each do |chatter|
        begin
          chatter.print message unless chatter == sender
        rescue
          @chatters.delete chatter
        end
      end
    end
  end

  
  def serve io
    io.print 'Name: '
    name = io.gets

    
    return if name.nil?

    name.strip!

    broadcast 

    
    @mutex.synchronize do
      @chatters << io
    end

    
    loop do
      message = io.gets

      if message
        broadcast , io
      else
        break
      end
    end

    broadcast 
  end
end






ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join