Skip to content
Browse files

Move logic serverside into classes

  • Loading branch information...
1 parent b8d5c46 commit ac921463646d3e3cb3de75469c9ff31e1f7f315a @iain iain committed Dec 5, 2011
Showing with 91 additions and 24 deletions.
  1. +50 −0 lib/messenger.rb
  2. +32 −0 lib/pool.rb
  3. +9 −24 server.rb
View
50 lib/messenger.rb
@@ -0,0 +1,50 @@
+class Messenger
+
+ def self.perform(*args)
+ new(*args).perform
+ end
+
+ def initialize(all, sender, message)
+ @all, @sender, @message = all, sender, message
+ end
+
+ def perform
+ if preview?
+ listen
+ else
+ spam
+ spam_satisfaction
+ end
+ end
+
+ def hash
+ @hash ||= JSON.parse(@message)
+ end
+
+ def preview?
+ hash.fetch("args"){{}}["preview"]
+ end
+
+ def listen
+ @sender.send(@message)
+ end
+
+ def spam
+ @all.each do |receiver|
+ receiver.send(@message) unless me?(receiver)
+ end
+ end
+
+ def spam_satisfaction
+ @sender.send({action: "playingSoundToOthers", args: { listeners: others }}.to_json)
+ end
+
+ def others
+ @all.size - 1
+ end
+
+ def me?(receiver)
+ receiver == @sender
+ end
+
+end
View
32 lib/pool.rb
@@ -0,0 +1,32 @@
+class Pool
+
+ def initialize(sockets = [], messenger = Messenger)
+ @sockets = sockets
+ @messenger = messenger
+ end
+
+ def add(socket)
+ @sockets << socket
+ connection_change
+ end
+
+ def remove(socket)
+ @sockets.delete socket
+ connection_change
+ end
+
+ def message(socket, message)
+ @messenger.perform(@sockets, socket, message)
+ end
+
+ def connection_change
+ @sockets.each do |socket|
+ socket.send({action: "connectionChange", args: { listeners: connections}}.to_json)
+ end
+ end
+
+ def connections
+ @sockets.size
+ end
+
+end
View
33 server.rb
@@ -3,48 +3,33 @@
require 'em-websocket'
require 'json'
-sockets = []
+$:.unshift File.expand_path('../lib', __FILE__)
+
+require 'pool'
+require 'messenger'
HOST = '0.0.0.0'
PORT = 8080
-def connection_change(sockets)
- sockets.each do |socket|
- socket.send({action: "connectionChange", args: { listeners: sockets.size}}.to_json)
- end
-end
+pool = Pool.new
EventMachine.run do
EventMachine::WebSocket.start(host: HOST, port: PORT) do |socket|
socket.onopen do
puts "Socket opened"
- sockets << socket
- connection_change sockets
+ pool.add socket
end
socket.onmessage do |message|
- hash = JSON.parse(message)
- puts "Handling message: #{hash.inspect}"
-
- if hash.fetch("args"){{}}["preview"]
- puts "Playing preview"
- socket.send(message)
- else
- puts "Broadcasting sound to other sockets"
- sockets.each do |other_socket|
- other_socket.send(message) if other_socket != socket
- end
- socket.send({action: "playingSoundToOthers", args: { listeners: sockets.size - 1 }}.to_json)
- end
-
+ puts "Handling message: #{message}"
+ pool.message socket, message
end
socket.onclose do
puts "Socket closed"
- sockets.delete(socket)
- connection_change sockets
+ pool.remove socket
end
end

0 comments on commit ac92146

Please sign in to comment.
Something went wrong with that request. Please try again.