aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/lib/action_cable/connection/faye_client_socket.rb
blob: 06e92c5d522631ebad07dacc99ff077836f63f2c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
require "faye/websocket"

module ActionCable
  module Connection
    class FayeClientSocket
      def initialize(env, event_target, stream_event_loop, protocols)
        @env = env
        @event_target = event_target
        @protocols = protocols

        @faye = nil
      end

      def alive?
        @faye && @faye.ready_state == Faye::WebSocket::API::OPEN
      end

      def transmit(data)
        connect
        @faye.send data
      end

      def close
        @faye && @faye.close
      end

      def protocol
        @faye && @faye.protocol
      end

      def rack_response
        connect
        @faye.rack_response
      end

      private
        def connect
          return if @faye
          @faye = Faye::WebSocket.new(@env, @protocols)

          @faye.on(:open)    { |event| @event_target.on_open }
          @faye.on(:message) { |event| @event_target.on_message(event.data) }
          @faye.on(:close)   { |event| @event_target.on_close(event.reason, event.code) }
          @faye.on(:error)   { |event| @event_target.on_error(event.message) }
        end
    end
  end
end