From: Hugh Sasse Staff Elec Eng Date: 2002-08-15T01:15:59+09:00 Subject: RE: Problems with Marshal On Thu, 15 Aug 2002, Berger, Daniel wrote: > > -----Original Message----- > > From: Hugh Sasse Staff Elec Eng [mailto:hgs@dmu.ac.uk] > > > > How are you sending and receiving the data? > > Ok, I've narrowed it down partially to a newline issue with Marshal. Here Curious. I didn't expect marshal to make much use of whitespace... > are a sample client and server to demonstrate. Just start the server in one [...] > The question I have, then, is how do I make sure that the marshalled object > is properly newline terminated? When I wanted to do this I took the somewhat paranoid approach that the only characters which are guaranteed to be passable between systems are those that make up base64 -- which is why base64 was invented. See RFC989 Section 5.2 for details of this. #!/usr/local/bin/ruby -w # Routine to encode an object into a string for transmission. # Author: Hugh Sasse # Created: 07-APR-2000 # RCS Infromation: # $Revision: 1.3 $ # last put in RCS: $Date: 2000-12-12 11:36:17+00 $ # ID: $Id: Encode.rb,v 1.3 2000-12-12 11:36:17+00 hgs Exp hgs $ # This takes an object, and it uses Marshal to create a string. # It then converts that string to base 64. # Marshal is used even on strings so that the process is reversible. # If this file is executed directly (i.e. not using "require") then # it performs a basc self test. class Encoded include Marshal def decode @decoded end def encode @encoded end private def initialize(thing, code = true, depth=-1) if code == true @decoded = thing @encoded = [Marshal.dump(@decoded,depth)].pack("m") else @encoded = thing @decoded = Marshal.load(@encoded.unpack("m")[0]) end end end if __FILE__ == $0 print "Self test\n" # define an arbitrary class to save. class Fish def swim print "#{@name} is swimming\n" end def initialize(name) @name = name end end eric = Fish.new("Eric") # Build an arrray of varying things to save... x = [1,3.4,"hello!",{"this" => "that"},eric] p(x) e = Encoded.new(x, true, 20) # s is the string to decode... s = e.encode() p(s.type()) p(s) # decode it anew. New instance not a copy of the old f = Encoded.new(s,false) result = f.decode() p(result) p(result[-1].type()) # show that the las item is really of the class we defined. result[-1].swim() end > > Regards, > > Dan > Hugh