Class: Yaic::Socket
- Inherits:
-
Object
- Object
- Yaic::Socket
- Defined in:
- lib/yaic/socket.rb
Instance Method Summary collapse
- #connect ⇒ Object
- #disconnect ⇒ Object
-
#initialize(host, port, ssl: false, verify_mode: nil, connect_timeout: 30) ⇒ Socket
constructor
A new instance of Socket.
- #read ⇒ Object
- #state ⇒ Object
- #write(message) ⇒ Object
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
#connect ⇒ Object
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. end |
#disconnect ⇒ Object
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 |
#read ⇒ Object
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) rescue IO::WaitReadable rescue IOError, Errno::ECONNRESET nil end end end |
#state ⇒ Object
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() @monitor.synchronize do return if @socket.nil? = .dup << "\r\n" unless .end_with?("\r\n", "\n") begin @socket.write_nonblock() rescue IO::WaitWritable @write_queue << flush_write_queue end end end |