using System.IO; using System.Net; using System; namespace Com.Xagasoft.Gats { public class GatsStream { private Stream s; private MemoryStream ReadBuf; private int size = -1; private int version; private BinaryWriter bw = null; private BinaryReader br = null; public GatsStream( Stream s ) { this.s = s; this.ReadBuf = new MemoryStream(); } public GatsObject ReadObject() { if( size == -1 ) { for(;;) { version = s.ReadByte(); if( version == -1 ) return null; if( version > 0 ) break; } } if( br == null ) this.br = new BinaryReader( s ); switch( version ) { case 1: // Verion 1 of gats if( size == -1 ) size = IPAddress.NetworkToHostOrder( br.ReadInt32() )-5; byte[] buf = new byte[4096]; while( ReadBuf.Length < size ) { int goal = (int)(size-ReadBuf.Length); if( goal > 4096 ) goal = 4096; int amnt = s.Read( buf, 0, goal ); if( amnt <= 0 ) return null; ReadBuf.Write( buf, 0, amnt ); } ReadBuf.Seek( 0, SeekOrigin.Begin ); GatsObject ret = GatsObject.Read( ReadBuf ); ReadBuf.SetLength( 0 ); size = version = -1; return ret; } return null; } public void WriteObject( GatsObject obj ) { MemoryStream ms = new MemoryStream(); obj.Write( ms ); if( bw == null ) this.bw = new BinaryWriter( s ); bw.Write( (byte)1 ); bw.Write( IPAddress.HostToNetworkOrder( (int)ms.Length+5 ) ); bw.Write( ms.GetBuffer(), 0, (int)ms.Length ); } } }