Class: ProtoSocket

Inherits:
FlashConnection show all
Defined in:
lib/protolink/proto_socket.rb

Instance Method Summary collapse

Methods inherited from FlashConnection

#log, #receive_data, #receive_line, #send_json, #send_line, #to_s

Constructor Details

#initialize(connection, message_callback) ⇒ ProtoSocket

Returns a new instance of ProtoSocket.



3
4
5
6
7
# File 'lib/protolink/proto_socket.rb', line 3

def initialize(connection, message_callback)
  @connection = connection
  @message_callback = message_callback
  super()
end

Instance Method Details

#connection_completedObject



9
10
11
12
13
14
15
16
17
# File 'lib/protolink/proto_socket.rb', line 9

def connection_completed
  token           = @connection.current_user.communication_token
  
  send_json :operation => 'authenticate',
            :payload => {:type => 'web', :user_id => @connection.current_user.id, :token => token}
  
  periodic_ping
  disconnect_if_no_ping_received
end

#disconnect_if_no_ping_receivedObject



34
35
36
37
38
39
40
# File 'lib/protolink/proto_socket.rb', line 34

def disconnect_if_no_ping_received
  @ping_check ||= EventMachine.add_periodic_timer 30 do
    if @last_ping_received && @last_ping_received < (Time.now - 60)
      close_connection
    end      
  end
end

#periodic_pingObject



27
28
29
30
31
32
# File 'lib/protolink/proto_socket.rb', line 27

def periodic_ping
  @ping ||= EventMachine.add_periodic_timer 30 do
    # log "sending ping"
    send_json :operation => 'ping'
  end
end

#receive_json(json) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/protolink/proto_socket.rb', line 19

def receive_json(json)
  if json["trigger"] == "socket.ping_received"
    @last_ping_received = Time.now
    return
  end
  @message_callback.call(json)
end

#unbindObject



42
43
44
45
46
47
48
49
# File 'lib/protolink/proto_socket.rb', line 42

def unbind
  puts "DISCONNECTED"
  EventMachine::cancel_timer @ping
  EventMachine::cancel_timer @ping_check
  EventMachine::add_timer(30) {
    EventMachine.connect URI.parse(@connection.class.base_uri).host, 5000, ProtoSocket, @connection, @message_callback
  }
end