lib/dripdrop/handlers/websockets.rb in dripdrop-0.9.6 vs lib/dripdrop/handlers/websockets.rb in dripdrop-0.9.8
- old
+ new
@@ -1,39 +1,47 @@
require 'em-websocket'
-require 'json'
+
class DripDrop
class WebSocketHandler < BaseHandler
+ class SocketError < StandardError; attr_accessor :reason, :connection end
+
attr_reader :ws, :address, :thread
def initialize(address,opts={})
- @raw = false #Deal in strings or ZMQ::Message objects
- host, port = address.host, address.port.to_i
- @debug = opts[:debug] || false
+ @opts = opts
+ @raw = false #Deal in strings or ZMQ::Message objects
+ host, port = address.host, address.port.to_i
+ @message_class = @opts[:message_class] || DripDrop.default_message_class
+ @debug = @opts[:debug] || false
EventMachine::WebSocket.start(:host => host,:port => port,:debug => @debug) do |ws|
#A WebSocketHandler:Connection gets passed to all callbacks
dd_conn = Connection.new(ws)
- ws.onopen { @onopen_handler.call(dd_conn) if @onopen_handler }
+ ws.onopen { @onopen_handler.call(dd_conn) if @onopen_handler }
ws.onclose { @onclose_handler.call(dd_conn) if @onclose_handler }
- ws.onerror {|reason| @onerror_handler.call(reason, dd_conn) if @onerror_handler }
+ ws.onerror {|reason|
+ e = SocketError.new
+ e.reason = reason
+ e.connection = dd_conn
+ handle_error(e)
+ }
- ws.onmessage do |message|
+ ws.onmessage { |message|
if @onmessage_handler
begin
- message = DripDrop::Message.decode_json(message) unless @raw
+ message = @message_class.decode(message) unless @raw
+ @onmessage_handler.call(message,dd_conn)
rescue StandardError => e
- $stderr.write "Could not parse message: #{e.message}" if @debug
+ handle_error(e,dd_conn)
end
-
- @onmessage_handler.call(message,dd_conn)
end
- end
+ }
end
end
-
+
def on_recv(&block)
@raw = false
@onmessage_handler = block
self
end
@@ -51,15 +59,10 @@
def on_close(&block)
@onclose_handler = block
self
end
-
- def on_error(&block)
- @onerror_handler = block
- self
- end
end
class WebSocketHandler::Connection < BaseHandler
attr_reader :ws, :signature, :handler
@@ -67,9 +70,10 @@
@ws = ws
@signature = @ws.signature
end
def send_message(message)
- @ws.send(dd_messagify(message).to_hash.to_json)
+ encoded_message = dd_messagify(message).encoded
+ @ws.send(encoded_message)
end
end
end