using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections; using System.IO; namespace IvyBus { /// /// Description résumée de IvyStream. /// public class IvyStream : NetworkStream { BinaryReader input; BinaryWriter output; public IvyStream(Socket socket) : base( socket, true ) { input = new BinaryReader( new BufferedStream(this),Encoding.ASCII); output = new BinaryWriter( new BufferedStream(this), Encoding.ASCII); } /* the protocol magic numbers */ internal enum MessageType : ushort { Bye = 0, /* end of the peer */ AddRegexp = 1, /* the peer adds a regexp */ Msg = 2, /* the peer sends a message */ Error = 3, /* error message */ DelRegexp = 4, /* the peer removes one of his regex */ EndRegexp = 5, /* no more regexp in the handshake */ StartRegexp = 6, /* avoid race condition in concurrent connexions */ DirectMsg = 7, /* the peer sends a direct message */ Die = 8, /* the peer wants us to quit */ Ping = 9, /* checks the presence of the other */ Pong = 10, /* checks the presence of the other */ AddBinding = 11, /* other methods for binding message based on hash table */ DelBinding = 12, /* other methods for binding message based on hash table */ ApplicationId = 13, /* on start send my ID and priority */ }; /* * message Syntax: * this is a binary formated message use of network representation * * message Format: MessageType, id , length, string */ internal void sendMsg(MessageType type, int id, byte[] arg) { try { output.Write( (ushort)IPAddress.HostToNetworkOrder( (short)type ) ); output.Write( (ushort)IPAddress.HostToNetworkOrder( (short)id ) ); output.Write( (ushort)IPAddress.HostToNetworkOrder( (short)arg.Length ) ); output.Write( arg ); output.Flush(); } catch (IOException ie) { Console.Error.WriteLine("received an exception: " + ie.Message); Console.Error.WriteLine(ie.StackTrace); } } internal bool receiveMsg(out MessageType type, out int id, out byte[] data) { int length = 0; data = null; id = 0; type = MessageType.Die; try { type = (MessageType)(ushort) IPAddress.NetworkToHostOrder( (short) input.ReadUInt16() ); id = (ushort) IPAddress.NetworkToHostOrder( (short) input.ReadUInt16()); length = (ushort) IPAddress.NetworkToHostOrder( (short) input.ReadUInt16()); data = input.ReadBytes( length ); } catch (EndOfStreamException nfe) { return false; } catch (FormatException nfe) { throw new IvyException("protocol error on msgType"); } return true; } } }