Created
October 16, 2017 21:54
-
-
Save michelson/ddfc9916ed07c98393406b6f4e894de9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'json' | |
require 'em-hiredis' | |
require 'faye/websocket' | |
require 'rack' | |
Faye::EventSource.class_eval do | |
attr_accessor :connected_at | |
end | |
# disable rack::lint so we can return a status code -1 | |
class Rack::Lint | |
def call(env) | |
@app.call(env) | |
end | |
end | |
module EventSockets | |
SOCKETS = {} | |
SETTINGS = { :connected => false } | |
class << self | |
def logger | |
@logger ||= Logger.new('./log/events.log') | |
end | |
def connect_to_redis | |
EM.run { | |
@redis = EM::Hiredis.connect("redis://#{AppConfig.redis[:events]}:6379") | |
} | |
pid = $$ | |
@redis.pubsub.subscribe(some_config) do |msg| | |
# code handling | |
end | |
SETTINGS[:connected] = true | |
end | |
def stop | |
puts "Stopping all sockets..." | |
SOCKETS.each { |s| s.close } | |
end | |
def call(env) | |
if Faye::EventSource.eventsource?(env) | |
connect_to_redis unless SETTINGS[:connected] | |
es = Faye::EventSource.new(env) | |
es.connected_at = Time.now | |
es.onclose = lambda do |event| | |
## code handing | |
end | |
# Return async Rack response | |
es.rack_response | |
else # Normal HTTP request | |
logger.error "Non EventSource request: #{env['HTTP_USER_AGENT']}" | |
[200, {'Content-Type' => 'text/plain'}, ['Hello']] | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment