Skip to content

Instantly share code, notes, and snippets.

@naive
Created March 27, 2011 08:31
Show Gist options
  • Save naive/889038 to your computer and use it in GitHub Desktop.
Save naive/889038 to your computer and use it in GitHub Desktop.
Wait for connection close and stop
class Server
attr_accessor :connections
def initialize
@connections = []
end
def start
@signature = EventMachine.start_server('0.0.0.0', 3000, Connection) do |con|
con.server = self
end
end
def stop
EventMachine.stop_server(@signature)
unless wait_for_connections_and_stop
# Still some connections running, schedule a check later
EventMachine.add_periodic_timer(1) { wait_for_connections_and_stop }
end
end
def wait_for_connections_and_stop
if @connections.empty?
EventMachine.stop
true
else
puts "Waiting for #{@connections.size} connection(s) to finish ..."
false
end
end
end
class Connection < EventMachine::Connection
attr_accessor :server
def unbind
server.connections.delete(self)
end
end
EventMachine::run {
s = Server.new
s.start
puts "New server listening"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment