Class: Krakow::Ksocket
- Inherits:
-
Object
- Object
- Krakow::Ksocket
- Includes:
- Celluloid, Utils::Lazy
- Defined in:
- lib/krakow/ksocket.rb
Instance Attribute Summary collapse
- #buffer ⇒ String readonly
Instance Method Summary collapse
-
#closedown_socket ⇒ Object
Teardown helper.
-
#get(n) ⇒ String
(also: #recv, #read, #sysread, #readpartial)
Fetch bytes from socket.
-
#initialize(args = {}) ⇒ self
constructor
Create new socket wrapper.
-
#put(line) ⇒ Integer
(also: #write)
Push bytes to socket.
-
#read_loop ⇒ Object
Read from socket and push into local Queue.
-
#reading? ⇒ TrueClass, FalseClass
Read loop enabled.
- #socket ⇒ Socket
Methods included from Utils::Lazy
Methods included from Utils::Logging
Constructor Details
#initialize(args = {}) ⇒ self
Create new socket wrapper
30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/krakow/ksocket.rb', line 30 def initialize(args={}) if(args[:socket]) @socket = args[:socket] else unless([:host, :port].all?{|k| args.include?(k)}) raise ArgumentError.new 'Missing required arguments. Expecting `:socket` or `:host` and `:port`.' end @socket = TCPSocket.new(args[:host], args[:port]) end @buffer = '' async.read_loop end |
Instance Attribute Details
#buffer ⇒ String (readonly)
11 12 13 |
# File 'lib/krakow/ksocket.rb', line 11 def buffer @buffer end |
Instance Method Details
#closedown_socket ⇒ Object
Teardown helper
16 17 18 19 20 21 |
# File 'lib/krakow/ksocket.rb', line 16 def closedown_socket @writing = @reading = false if(socket && !socket.closed?) socket.close end end |
#get(n) ⇒ String Also known as: recv, read, sysread, readpartial
Fetch bytes from socket
72 73 74 75 76 77 |
# File 'lib/krakow/ksocket.rb', line 72 def get(n) until(buffer.length >= n) wait(:content_read) end buffer.slice!(0, n) end |
#put(line) ⇒ Integer Also known as: write
Push bytes to socket
87 88 89 |
# File 'lib/krakow/ksocket.rb', line 87 def put(line) socket{|s| s.write(line)} end |
#read_loop ⇒ Object
Read from socket and push into local Queue
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/krakow/ksocket.rb', line 49 def read_loop unless(reading?) @reading = true while(reading?) res = defer do Kernel.select([socket], nil, nil, nil) socket{|s| s.readpartial(1024)} end if(res) debug "Received content from socket: #{res.inspect}" buffer << res signal(:content_read) else debug 'No content received from socket read. Ignoring.' end end end end |
#reading? ⇒ TrueClass, FalseClass
Returns read loop enabled.
44 45 46 |
# File 'lib/krakow/ksocket.rb', line 44 def reading? !!@reading end |
#socket ⇒ Socket
93 94 95 96 97 98 99 |
# File 'lib/krakow/ksocket.rb', line 93 def socket if(block_given?) yield @socket else @socket end end |