%w(em-websocket pp socket).each do |lib| require lib end class Client attr_reader :ip, :port def initialize(ws) @ws,@port,@ip = ws,*Socket.unpack_sockaddr_in(ws.get_peername) end def send(message) @ws.send(message) end end class Clients def initialize() @clients = [] end def add(client) @clients.push(client) end def del(client) @clients.delete(client) end def send(message) @clients.each do |client| client.send message end end end class Chat def initialize() @clients = Clients.new end def start() EventMachine.run do EventMachine::WebSocket.start(:host => "127.0.0.1", :port => 4096) do |ws| client = Client.new(ws) ws.onopen do @clients.add(client) @clients.send("client #{client.ip}:#{client.port} joined the chat") end ws.onmessage do |message| puts %Q{[#{Time.now}] received "#{message}" from #{client.ip}:#{client.port}} @clients.send("#{Time.now} #{message}") end ws.onclose do @clients.del(client); puts "WebSocket closed" end end end end end chat=Chat.new chat.start