Class: MTProto::Transport::TCPConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/mtproto/transport/tcp_connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, codec) ⇒ TCPConnection

Returns a new instance of TCPConnection.



13
14
15
16
17
18
# File 'lib/mtproto/transport/tcp_connection.rb', line 13

def initialize(host, port, codec)
  @host = host
  @port = port
  @codec = codec
  @socket = nil
end

Instance Attribute Details

#codecObject (readonly)

Returns the value of attribute codec.



11
12
13
# File 'lib/mtproto/transport/tcp_connection.rb', line 11

def codec
  @codec
end

#hostObject (readonly)

Returns the value of attribute host.



11
12
13
# File 'lib/mtproto/transport/tcp_connection.rb', line 11

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



11
12
13
# File 'lib/mtproto/transport/tcp_connection.rb', line 11

def port
  @port
end

Instance Method Details

#closeObject



49
50
51
52
53
54
55
56
57
# File 'lib/mtproto/transport/tcp_connection.rb', line 49

def close
  return unless @socket

  @socket.close
rescue StandardError
  nil
ensure
  @socket = nil
end

#connect!Object



20
21
22
23
24
25
26
# File 'lib/mtproto/transport/tcp_connection.rb', line 20

def connect!
  return if connected?

  @socket = TCPSocket.new(@host, @port)

  send_init_tag if @codec.class.const_defined?(:TAG)
end

#connected?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/mtproto/transport/tcp_connection.rb', line 28

def connected?
  !@socket.nil? && !@socket.closed?
end

#recv(timeout: 60) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/mtproto/transport/tcp_connection.rb', line 39

def recv(timeout: 60)
  raise ConnectionError, 'Not connected' unless connected?

  Timeout.timeout(timeout) do
    read_packet
  end
rescue Timeout::Error
  raise ConnectionError, 'Receive timeout'
end

#send(data) ⇒ Object

Raises:



32
33
34
35
36
37
# File 'lib/mtproto/transport/tcp_connection.rb', line 32

def send(data)
  raise ConnectionError, 'Not connected' unless connected?

  encoded = @codec.encode_packet(data)
  @socket.write(encoded)
end