Class: Termfront::Network::Connection
- Inherits:
-
Object
- Object
- Termfront::Network::Connection
- Defined in:
- lib/termfront/network/connection.rb
Instance Attribute Summary collapse
-
#rtt ⇒ Object
readonly
Returns the value of attribute rtt.
Instance Method Summary collapse
- #close ⇒ Object
- #connect(host, port) ⇒ Object
- #connected? ⇒ Boolean
-
#initialize ⇒ Connection
constructor
A new instance of Connection.
- #ping(now) ⇒ Object
- #receive ⇒ Object
- #send_msg(hash) ⇒ Object
- #socket ⇒ Object
Constructor Details
#initialize ⇒ Connection
Returns a new instance of Connection.
12 13 14 15 16 17 |
# File 'lib/termfront/network/connection.rb', line 12 def initialize @sock = nil @buf = +"" @ping_ts = 0 @rtt = 0 end |
Instance Attribute Details
#rtt ⇒ Object (readonly)
Returns the value of attribute rtt.
10 11 12 |
# File 'lib/termfront/network/connection.rb', line 10 def rtt @rtt end |
Instance Method Details
#close ⇒ Object
72 73 74 75 76 77 78 79 |
# File 'lib/termfront/network/connection.rb', line 72 def close begin @sock&.close rescue StandardError nil end @sock = nil end |
#connect(host, port) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/termfront/network/connection.rb', line 19 def connect(host, port) tcp = TCPSocket.new(host, port) tcp.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) ctx = OpenSSL::SSL::SSLContext.new ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE @sock = OpenSSL::SSL::SSLSocket.new(tcp, ctx) @sock.hostname = host if @sock.respond_to?(:hostname=) @sock.sync = true @sock.connect end |
#connected? ⇒ Boolean
81 82 83 |
# File 'lib/termfront/network/connection.rb', line 81 def connected? !@sock.nil? end |
#ping(now) ⇒ Object
85 86 87 88 |
# File 'lib/termfront/network/connection.rb', line 85 def ping(now) @ping_ts = now send_msg({ t: "ping", ts: (now * 1000).to_i }) end |
#receive ⇒ Object
39 40 41 42 43 44 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 70 |
# File 'lib/termfront/network/connection.rb', line 39 def receive return [] unless @sock = [] while IO.select([@sock], nil, nil, 0) begin data = @sock.read_nonblock(4096) @buf << data while (nl = @buf.index("\n")) line = @buf.slice!(0, nl + 1) begin msg = JSON.parse(line, symbolize_names: true) if msg[:t] == "pong" @rtt = ((clock - @ping_ts) * 1000).to_i if @ping_ts > 0 else << msg end rescue JSON::ParserError next end end rescue IO::WaitReadable break rescue EOFError, Errno::ECONNRESET, IOError, OpenSSL::SSL::SSLError break end end end |
#send_msg(hash) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/termfront/network/connection.rb', line 31 def send_msg(hash) return unless @sock @sock.write(JSON.generate(hash) + "\n") rescue Errno::EPIPE, Errno::ECONNRESET, IOError, OpenSSL::SSL::SSLError nil end |
#socket ⇒ Object
90 91 92 |
# File 'lib/termfront/network/connection.rb', line 90 def socket @sock end |