blob: e1bba916ac67e23b028d19b69d3b4b277595a7ec (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
/*
* Copyright (C) 2007-2012 Xagasoft, All rights reserved.
*
* This file is part of the libgats library and is released under the
* terms of the license contained in the file LICENSE.
*/
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 );
}
}
}
|