Class: Distributor::Packet

Inherits:
Object
  • Object
show all
Defined in:
lib/distributor/packet.rb

Constant Summary collapse

PROTOCOL_VERSION =
1

Class Method Summary collapse

Class Method Details

.pack(num) ⇒ Object



36
37
38
# File 'lib/distributor/packet.rb', line 36

def self.pack(num)
  [num].pack("N")
end

.parse(io) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/distributor/packet.rb', line 22

def self.parse(io)
  @@input ||= Mutex.new
  @@input.synchronize do
    header = io.read(4)
    return if header.nil?
    raise "invalid header" unless header == "DIST"
    version = unpack(io.read(4))
    channel = unpack(io.read(4))
    length  = unpack(io.read(4))
    data    = io.read(length)
    return [ channel, data ]
  end
end

.unpack(string) ⇒ Object



40
41
42
# File 'lib/distributor/packet.rb', line 40

def self.unpack(string)
  string.unpack("N").first
end

.write(io, channel, data) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/distributor/packet.rb', line 9

def self.write(io, channel, data)
  @@output ||= Mutex.new
  @@output.synchronize do
    buffer = StringIO.new
    buffer.write "DIST"
    buffer.write pack(PROTOCOL_VERSION)
    buffer.write pack(channel)
    buffer.write pack(data.length)
    buffer.write data
    io.write buffer.string
  end
end