Yesterday we looked at simple web server to serve as our chat server. Today let’s work towards the first class. Adding clients to the pool. First we update the TCPServer to accept multiple connections with a Thread.start.

require 'socket'

server = TCPServer.new 2000

loop do
  Thread.start(server.accept) do |connection|
    conn.puts "Up and running"
    conn.close
  end
end

class Chat
  def initialize
    @clients = []
    @client_id = 0 
  end

  def insert(server)
    server.on(:accept) do |stream|
      add_connection(stream)
    end 
  end

 def add_connection(stream)
    id = (@client_id += 1)
    send("user ##{id} connected\n")

    stream.on(:data) do |chat|
      send("User ##{id} said: #{chat}")
    end

    stream.on(:close) do
      @clients.delete(stream)
      send("User ##{id} exited chat")
    end

    @clients << stream
  end

  def send(msg)
    @clients.each do |stream|
      stream << msg
    end
  end

end

# Example
# io = TCPServer.new 2000
# server = Chat.new
# server.add(io)
# io.start

🙂

Leave a Reply

Screen Shot 2013-12-08 at 9.49.35 PM

I have helped a dozen companies build and optimize their engineering teams to deliver great products.

Let’s work together and I can align your business needs with your technology initiatives.