Class: Krakow::Ksocket

Inherits:
Object
  • Object
show all
Includes:
Celluloid, Utils::Lazy
Defined in:
lib/krakow/ksocket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils::Lazy

included

Methods included from Utils::Logging

level=, #log

Constructor Details

#initialize(args = {}) ⇒ self

Create new socket wrapper

Parameters:

  • args (Hash) (defaults to: {})

Options Hash (args):

  • :socket (Socket-ish)
  • :host (String)
  • :port (Integer)


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

#bufferString (readonly)

Returns:

  • (String)


11
12
13
# File 'lib/krakow/ksocket.rb', line 11

def buffer
  @buffer
end

Instance Method Details

#closedown_socketObject

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

Parameters:

  • n (Integer)

Returns:

  • (String)


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

Parameters:

  • line (String)

Returns:

  • (Integer)


87
88
89
# File 'lib/krakow/ksocket.rb', line 87

def put(line)
  socket{|s| s.write(line)}
end

#read_loopObject

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.

Returns:

  • (TrueClass, FalseClass)

    read loop enabled



44
45
46
# File 'lib/krakow/ksocket.rb', line 44

def reading?
  !!@reading
end

#socketSocket

Returns:

  • (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