lib/websocket/eventmachine/base.rb in websocket-eventmachine-base-1.0.3 vs lib/websocket/eventmachine/base.rb in websocket-eventmachine-base-1.1.0

- old
+ new

@@ -23,11 +23,13 @@ # Called when connection is opened. # No parameters are passed to block def onopen(&blk); @onopen = blk; end # Called when connection is closed. - # No parameters are passed to block + # Two parameters are passed to block: + # code - status code + # reason - optional reason for closure def onclose(&blk); @onclose = blk; end # Called when error occurs. # One parameter passed to block: # error - string with error message @@ -118,11 +120,11 @@ # @private def unbind unless @state == :closed @state = :closed close - trigger_onclose('') + trigger_onclose(1002, '') end end ####################### ### Private methods ### @@ -135,17 +137,24 @@ callback = instance_variable_get("@#{m}") callback.call if callback end end - ['onerror', 'onping', 'onpong', 'onclose'].each do |m| + ['onerror', 'onping', 'onpong'].each do |m| define_method "trigger_#{m}" do |data| callback = instance_variable_get("@#{m}") callback.call(data) if callback end end + ['onclose'].each do |m| + define_method "trigger_#{m}" do |code, reason| + callback = instance_variable_get("@#{m}") + callback.call(code, reason) if callback + end + end + def trigger_onmessage(data, type) @onmessage.call(data, type) if @onmessage end def handle_connecting(data) @@ -156,11 +165,11 @@ @frame = incoming_frame.new(:version => @handshake.version) @state = :open trigger_onopen handle_open(@handshake.leftovers) if @handshake.leftovers else - trigger_onerror(@handshake.error) + trigger_onerror(@handshake.error.to_s) close end end def handle_open(data) @@ -169,11 +178,11 @@ if @state == :open case frame.type when :close @state = :closing close - trigger_onclose(frame.to_s) + trigger_onclose(frame.code, frame.data) when :ping pong(frame.to_s) trigger_onping(frame.to_s) when :pong trigger_onpong(frame.to_s) @@ -192,18 +201,19 @@ def handle_error(error) error_code = case error when :invalid_payload_encoding then 1007 else 1002 end + trigger_onerror(error.to_s) close(error_code) unbind end def handle_closing(data) unless @state == :closed @state = :closed close - trigger_onclose('') + trigger_onclose(1000, '') end end def debug(description, data) return unless @debug