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.
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.
How can I make the server start deserialization in a way that it waits for all associated bytes are completed being sent?
Or do you think there is another problem?
Here is the code:
// Server listens to socket
private void ReadData(object obj)
{
Socket client = (Socket)obj;
while (true)
{
if (client.Available > 0)
{
byte[] buffer = new byte[client.Available];
client.Receive(buffer);
ServerCommandBase cmd = CommandReader.ReadSrvCommand(buffer);
cmd.Execute(context);
}
}
}
//CommandReader class
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);
}
}
// Serialization / Deserialization class
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");
}
stream.Position = 0;
return stream.ToArray();
}
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;
}
}