On Mon, Mar 31, 2003 at 03:08:49AM +0900, Bill Kelly wrote:
> From: "gabriele renzi" <surrender_it / rc1.vip.lng.yahoo.com>
> >
> > I need to write a value (it should be a Fixnum, but I'm not sure) over
> > a TCPSocket.
> > How can I write it in a typical "4 bytes, network byte order" style?
> > 
> > And what if I need to compose a byte and send it over the network?
> > Is BitVector the only choice?
> 
> Array#pack is probably what you're looking for...
> http://www.rubycentral.com/ref/ref_c_array.html#pack
> (the table showing the template characters for pack is a
> few pages up in that document... search for "Template
> characters for Array#pack")

For an example of this in real code, install druby and look at drb/drb.rb
functions 'dump' and 'load', which send or receive a marshalled object
preceded by a 4-byte size value:

    def dump(obj)
      obj = DRbObject.new(obj) if obj.kind_of? DRbUndumped
      begin
        str = Marshal::dump(obj)
      rescue
        str = Marshal::dump(DRbObject.new(obj))
      end
      [str.size].pack('N') + str
    end

    def load(soc)
      sz = soc.read(4)  # sizeof (N)
      raise(DRbConnError, 'connection closed') if sz.nil?
      raise(DRbConnError, 'premature header') if sz.size < 4
      sz = sz.unpack('N')[0]
      raise(DRbConnError, "too large packet #{sz}") if @load_limit < sz
      str = soc.read(sz)
      ... snip rest

Regards,

Brian.