[ Foro de C# ]

BinaryReader AutoMapp

04-Feb-2017 17:37
Juan Rios
1 Respuestas

Buenas tardes, tengo un servidor y un cliente, el servidor recibe mensajes del cliente auto asignados en el servidor así

public override ushort Id => 10100; este seria el primer paquete que recibe el servidor por parte del cliente, este mensaje esta escrito en el archivo HandshakeRequestMessage.cs de la carpeta mensajes y su contenido es:

public class HandshakeRequestMessage : Message
   {
       /// <summary>
       ///     AppStore.
       /// </summary>
       public int AppStore;

       /// <summary>
       ///     Build.
       /// </summary>
       public int Build;

       /// <summary>
       ///     Device type.
       /// </summary>
       public int DeviceType;

       /// <summary>
       ///     Key version.
       /// </summary>
       public int KeyVersion;

       /// <summary>
       ///     Major version.
       /// </summary>
       public int MajorVersion;

       /// <summary>
       ///     Hash string.
       /// </summary>
       public string MasterHash;

       /// <summary>
       ///     Minor version.
       /// </summary>
       public int MinorVersion;

       /// <summary>
       ///     Protocol.
       /// </summary>
       public int Protocol;

       /// <summary>
       ///     Gets the ID of the <see cref="HandshakeRequestMessage" />.
       /// </summary>
       public override ushort Id => 10100;

       /// <summary>
       ///     Reads the <see cref="HandshakeRequestMessage" /> from the specified <see cref="MessageReader" />.
       /// </summary>
       /// <param name="reader">
       ///     <see cref="MessageReader" /> that will be used to read the <see cref="HandshakeRequestMessage" />.
       /// </param>
       /// <exception cref="ArgumentNullException"><paramref name="reader" /> is null.</exception>
       public override void ReadMessage(MessageReader reader)
       {
           ThrowIfReaderNull(reader);

           Protocol = reader.ReadInt32();
           KeyVersion = reader.ReadInt32();
           MajorVersion = reader.ReadInt32();
           Build = reader.ReadInt32();
           MinorVersion = reader.ReadInt32();
           MasterHash = reader.ReadString();
           DeviceType = reader.ReadInt32();
           AppStore = reader.ReadInt32();
       }

       /// <summary>
       ///     Writes the <see cref="HandshakeRequestMessage" /> to the specified <see cref="MessageWriter" />.
       /// </summary>
       /// <param name="writer">
       ///     <see cref="MessageWriter" /> that will be used to write the <see cref="HandshakeRequestMessage" />.
       /// </param>
       /// <exception cref="ArgumentNullException"><paramref name="writer" /> is null.</exception>
       public override void WriteMessage(MessageWriter writer)
       {
           ThrowIfWriterNull(writer);

           writer.Write(Protocol);
           writer.Write(KeyVersion);
           writer.Write(MajorVersion);
           writer.Write(Build);
           writer.Write(MinorVersion);
           writer.Write(MasterHash);
           writer.Write(DeviceType);
           writer.Write(AppStore);
       }
   }

Hasta aquí todo bien bien, ahora tengo que rellenar los demás mensajes identificando cada mensaje que envía el cliente, para ello e probado todo pero sin éxito, llevo dos meses con esto y no hay forma... estoy muy desesperado... lo que tengo que saber es por ejemplo en el siguiente archivo:

public override ushort Id => 10101; (LoginRequestMessage.cs)

tengo puesto:

/// <summary>
   /// Message that is sent by the client to the server to request
   /// for a login.
   /// </summary>
   public class LoginRequestMessage : Message
   {
       /// <summary>
       /// Initializes a new instance of the <see cref="LoginRequestMessage"/> class.
       /// </summary>
       public LoginRequestMessage()
       {
           // Space
       }
       /// <summary>
       ///     Debug
       /// </summary>
       /// <param name="message"></param>
       [Conditional("DEBUG")]
       public static void DebugPrintTrace(Object message)
       {
           var stackTrace = new StackTrace(true);
           var sf = stackTrace.GetFrame(1);
           var str = sf.GetFileLineNumber() + " "
                     + Path.GetFileNameWithoutExtension(sf.GetFileName()) + ": "
                     + sf.GetMethod().Name + " ";
           Console.WriteLine(str + message.ToString());
       }

       //public long Unknown;


       /// <summary>
       ///  Gets the ID of the <see cref="LoginRequestMessage"/>.
       /// </summary>
       public override ushort Id => 10101;

       public static long baseStreamLength { get; private set; }

       /// <summary>
       /// Reads the <see cref="LoginRequestMessage"/> from the specified <see cref="MessageReader"/>.
       /// </summary>
       /// <param name="reader">
       /// <see cref="MessageReader"/> that will be used to read the <see cref="LoginRequestMessage"/>.
       /// </param>
       /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
       public override void ReadMessage(MessageReader reader)
       {
           baseStreamLength = reader.BaseStream.Length;
           ThrowIfReaderNull(reader);
           long baseStreamPos = reader.BaseStream.Position;
           DebugPrintTrace("arrayLength -> " + baseStreamLength); //244
           DebugPrintTrace("baseStreamPos -> " + baseStreamPos);

           try
           {
               for (int i = 0; i < baseStreamLength; i++)
               {
               DebugPrintTrace(i + " Unknown -> " + reader.ReadInt64());

               DebugPrintTrace("baseStreamPos -> " + baseStreamPos);
               }
           }
               catch (Exception ex)
               {
                   DebugPrintTrace(ex.ToString());
               }
               DebugPrintTrace("BaseStream.Position final -> " + reader.BaseStream.Position); //241

       }

Donde

DebugPrintTrace(i + " Unknown -> " + reader.ReadInt64());

me salen 29 lecturas de tipo long, hay mas pero no lee mas puesto que esas lecturas algunas son int64, otras int32, bool, byte y string y para que las lea todas tengo que averiguar en cada reader que tipo es en el orden y tipo correcto, para despues darles el nombre a cada uno...

la pregunta., hay algún código que me lo haga automáticamente la conversión o me autodetecte el TypeCode de cada reader? probé a guardar todos los bytes recibidos en un nuevo stream y despues convertirlos uno por uno a los varios tipos descritos anteriormente pero no funciono, también probé con serialize y deserealize pero no entiendo muy bien como funciona esto aun... muchas gracias de antemano por vuestro tiempo y ayuda.


11-Feb-2017 08:15
Juan Rios

Ya consegui la forma es lenta y tediosa pero funciona... igualmente si alguien encuentra alguna otra forma mas rapida sera bienvenida :)

for (long i = Reader.BaseStream.Position; i < Reader.BaseStream.Length; i++)
{
Console.WriteLine(this.Reader.ReadChar() + " pos:" + Reader.BaseStream.Position));
break;
}






(No se puede continuar esta discusión porque tiene más de dos meses de antigüedad. Si tienes dudas parecidas, abre un nuevo hilo.)