Class: Rpush::Daemon::TcpConnection

Inherits:
Object
  • Object
show all
Includes:
Loggable, Reflectable
Defined in:
lib/rpush/daemon/tcp_connection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#log_error, #log_info, #log_warn

Methods included from Reflectable

#reflect

Constructor Details

#initialize(app, host, port) ⇒ TcpConnection

Returns a new instance of TcpConnection.



15
16
17
18
19
20
21
22
# File 'lib/rpush/daemon/tcp_connection.rb', line 15

def initialize(app, host, port)
  @app = app
  @host = host
  @port = port
  @certificate = app.certificate
  @password = app.password
  written
end

Instance Attribute Details

#last_writeObject

Returns the value of attribute last_write.



9
10
11
# File 'lib/rpush/daemon/tcp_connection.rb', line 9

def last_write
  @last_write
end

Class Method Details

.idle_periodObject



11
12
13
# File 'lib/rpush/daemon/tcp_connection.rb', line 11

def self.idle_period
  30.minutes
end

Instance Method Details

#closeObject



29
30
31
32
33
34
35
# File 'lib/rpush/daemon/tcp_connection.rb', line 29

def close
  begin
    @ssl_socket.close if @ssl_socket
    @tcp_socket.close if @tcp_socket
  rescue IOError
  end
end

#connectObject



24
25
26
27
# File 'lib/rpush/daemon/tcp_connection.rb', line 24

def connect
  @ssl_context = setup_ssl_context
  @tcp_socket, @ssl_socket = connect_socket
end

#read(num_bytes) ⇒ Object



37
38
39
# File 'lib/rpush/daemon/tcp_connection.rb', line 37

def read(num_bytes)
  @ssl_socket.read(num_bytes)
end

#reconnectObject



71
72
73
74
# File 'lib/rpush/daemon/tcp_connection.rb', line 71

def reconnect
  close
  @tcp_socket, @ssl_socket = connect_socket
end

#select(timeout) ⇒ Object



41
42
43
# File 'lib/rpush/daemon/tcp_connection.rb', line 41

def select(timeout)
  IO.select([@ssl_socket], nil, nil, timeout)
end

#write(data) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rpush/daemon/tcp_connection.rb', line 45

def write(data)
  reconnect_idle if idle_period_exceeded?

  retry_count = 0

  begin
    write_data(data)
  rescue Errno::EPIPE, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError, IOError => e
    retry_count += 1;

    if retry_count == 1
      log_error("Lost connection to #{@host}:#{@port} (#{e.class.name}), reconnecting...")
      reflect(:apns_connection_lost, @app, e) # deprecated
      reflect(:tcp_connection_lost, @app, e)
    end

    if retry_count <= 3
      reconnect
      sleep 1
      retry
    else
      raise TcpConnectionError, "#{@app.name} tried #{retry_count-1} times to reconnect but failed (#{e.class.name})."
    end
  end
end