Created
February 9, 2011 18:58
-
-
Save elisehuard/819022 to your computer and use it in GitHub Desktop.
(minimal) mongrel2 handler in ruby
This file contains 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 'zmq' | |
require 'json' | |
handler_ctx = ZMQ::Context.new(1) | |
# receive and response for mongrel2 handlers | |
# queue address corresponds to what's in the configuration | |
recv_queue = handler_ctx.socket(ZMQ::PULL) | |
recv_queue.connect("tcp://127.0.0.1:9999") | |
response_publisher = handler_ctx.socket(ZMQ::PUB) | |
response_publisher.connect("tcp://127.0.0.1:9998") | |
response_publisher.setsockopt(ZMQ::IDENTITY, "82209006-86FF-4982-B5EA-D1E29E55D481") | |
stop_queue = handler_ctx.socket(ZMQ::PULL) | |
stop_queue.connect("ipc://shutdown_queue") | |
# queue to broadcast to all clients | |
eventsource_queue = handler_ctx.socket(ZMQ::PULL) | |
eventsource_queue.connect("ipc://eventsource_queue") | |
puts "blocking operation until a message is received, on any queue" | |
selected_queue = ZMQ.select([recv_queue, stop_queue, eventsource_queue]) | |
# establish connection | |
puts "establishing connection" | |
# Request comes in as "UUID ID PATH SIZE:HEADERS,SIZE:BODY," | |
sender_uuid, client_id, request_path, request_message = recv_queue.recv(0).split(' ', 4) | |
len, rest = request_message.split(':', 2) | |
headers = JSON.parse(rest[0...len.to_i]) | |
len, rest = rest[(len.to_i+1)..-1].split(':', 2) | |
body = rest[0...len.to_i] | |
# Respond with the opening EventSource information | |
puts "connecting ..." | |
headers = {} | |
headers['Content-Type'] = 'text/event-stream' | |
headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT' | |
headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate' | |
headers['Pragma'] = 'no-cache' | |
headers_s = headers.map{|k, v| "%s: %s" % [k,v]}.join("\r\n") | |
content_body = ": time stream\nretry: 5000\n\n"; | |
response_value = "#{sender_uuid} #{client_id.to_s.length}:#{client_id}, HTTP/1.1 200 OK\r\n#{headers_s}\r\n\r\n#{content_body}" | |
response_publisher.send(response_value, 0) | |
puts "sending a message" | |
# message | |
# sender_uuid corresponds to what's in mongrel configuration for send_spec | |
sender_uuid = '54c6755b-9628-40a4-9a2d-cc82a816345e' | |
message = "id: 1\r\ndata: O HAI\r\n\r\n" | |
response_value = "#{sender_uuid} #{client_id.to_s.length}:#{client_id}, #{message}" | |
response_publisher.send(response_value, 0) | |
puts "shutdown the connection" | |
ctx = ZMQ::Context.new(1) | |
stop_push_queue = ctx.socket(ZMQ::PUSH) | |
trap('INT') do # Send a message to shutdown on SIGINT | |
stop_push_queue.bind("ipc://shutdown_queue") | |
stop_push_queue.send("shutdown") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment