Class: Yaic::Socket

Inherits:
Object
  • Object
show all
Defined in:
lib/yaic/socket.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port, ssl: false, verify_mode: nil, connect_timeout: 30) ⇒ Socket

Returns a new instance of Socket.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/yaic/socket.rb', line 12

def initialize(host, port, ssl: false, verify_mode: nil, connect_timeout: 30)
  @host = host
  @port = port
  @ssl = ssl
  @verify_mode = verify_mode || OpenSSL::SSL::VERIFY_NONE
  @connect_timeout = connect_timeout

  @socket = nil
  @read_buffer = String.new(encoding: Encoding::ASCII_8BIT)
  @write_queue = []
  @state = :disconnected
  @monitor = Monitor.new
end

Instance Method Details

#connectObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/yaic/socket.rb', line 26

def connect
  tcp_socket = TCPSocket.new(@host, @port, connect_timeout: @connect_timeout)
  tcp_socket.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_KEEPALIVE, true)

  @monitor.synchronize do
    @socket = @ssl ? wrap_ssl(tcp_socket) : tcp_socket
    @state = :connecting
  end
rescue Errno::ETIMEDOUT, Errno::EHOSTUNREACH, Errno::ECONNREFUSED, IO::TimeoutError, SocketError => e
  raise Yaic::ConnectionError, e.message
end

#disconnectObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/yaic/socket.rb', line 38

def disconnect
  @monitor.synchronize do
    return if @state == :disconnected

    begin
      @socket&.close
    rescue
      nil
    end
    @socket = nil
    @read_buffer.clear
    @write_queue.clear
    @state = :disconnected
  end
end

#readObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/yaic/socket.rb', line 54

def read
  @monitor.synchronize do
    return nil if @socket.nil?

    begin
      data = @socket.read_nonblock(4096)
      buffer_data(data)
      extract_message
    rescue IO::WaitReadable
      extract_message
    rescue IOError, Errno::ECONNRESET
      nil
    end
  end
end

#stateObject



8
9
10
# File 'lib/yaic/socket.rb', line 8

def state
  @monitor.synchronize { @state }
end

#write(message) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/yaic/socket.rb', line 70

def write(message)
  @monitor.synchronize do
    return if @socket.nil?

    message = message.dup
    message << "\r\n" unless message.end_with?("\r\n", "\n")

    begin
      @socket.write_nonblock(message)
    rescue IO::WaitWritable
      @write_queue << message
      flush_write_queue
    end
  end
end