title: Deserialization Failure - C#
body: <p>I've written some code which is a mini simple imitation of messenger program.
  In the program; when the user signs out, instance of my LogOutCommand class is prepared by client program, serialized, and sent to server. When the server receives the LogOutCommand, it deserializes and invokes Execute method of the class, which performs db operations, etc. </p>
  
  <p>The problem is that, sometimes Server can deserialize very well, but sometimes fails.
  As far as I understand, server sometimes starts deserialization before associated bytes are sent totally and accurately. </p>
  
  <p>How can I make the server start deserialization in a way that it waits for all associated bytes are completed being sent?</p>
  
  <p>Or do you think there is another problem?</p>
  
  <p>Here is the code:</p>
  
  <p>// Server listens to socket</p>
  
  <pre><code>    private void ReadData(object obj)
      {
          Socket client = (Socket)obj;
  
          while (true)
          {
              if (client.Available &gt; 0)
              {
                  byte[] buffer = new byte[client.Available];
                  client.Receive(buffer);
                  ServerCommandBase cmd = CommandReader.ReadSrvCommand(buffer);
                  cmd.Execute(context);
  
              }
          }
      }
  </code></pre>
  
  <p>//CommandReader class</p>
  
  <pre><code>public class CommandReader
  {
      public static ServerCommandBase ReadSrvCommand(byte[] buffer)
      {
          return (ServerCommandBase)SerializationUtility.SerializationHelper.Deserialize(buffer);
      }
      public static ClientCommandBase ReadCliCommand(byte[] buffer)
      {
          return (ClientCommandBase)SerializationUtility.SerializationHelper.Deserialize(buffer);
      }
  
  }
  </code></pre>
  
  <p>// Serialization / Deserialization class</p>
  
  <p>public class SerializationHelper
      {
          public static byte[] Serialize(object obj)
          {
              BinaryFormatter formatter = new BinaryFormatter();
              MemoryStream stream = new MemoryStream();
              try
              {
                  formatter.Serialize(stream, obj);
              }
              catch (Exception)
              {
                  MessageBox.Show("Serialize Edilemiyor");
              }<br>
              stream.Position = 0;
              return stream.ToArray();
          }</p>
  
  <pre><code>    public static object Deserialize(byte[] byteArr)
      {
          BinaryFormatter formatter = new BinaryFormatter();
          MemoryStream ms = new MemoryStream(byteArr);
          ms.Position = 0;
          object retObj = null;
          try
          {
              retObj = formatter.Deserialize(ms);
          }
          catch (Exception)
          {
              MessageBox.Show("Cannot Be Deserialized!");
          }
  
          return retObj;
      }
  
  
  
  
  }
  </code></pre>