Search code examples
c#serializationserverclientprotocol-buffers

Deserialization is done only when I shut down client side


I'm trying to send packets from client to server over tcp stream. The client connects to the server and tries to send an image. However, the server gets the image only when I shutdown the client. (The server gets the image at the exact same moment I shutdown the client)

I use ProtoBuf-Net for serializing and deserializing. Here's my relevant code:

This is my client code :

// Connect to the client
client.Connect(Client.SERVER_IP, 1729);

// Capture screenshot
Bitmap captureBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
Screen.PrimaryScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Rectangle captureRectangle = Screen.PrimaryScreen.Bounds;
Graphics captureGraphics = Graphics.FromImage(captureBitmap);
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, 
captureRectangle.Size);

// Serialize the screenshot to the socket's stream
ImageConverter img = new ImageConverter();
Packet<byte[]> packet = new Packet<byte[]> { value = (byte[])img.ConvertTo(captureBitmap, typeof(byte[])), type = PacketType.IMAGE });
Serializer.SerializeWithLengthPrefix(stream, packet.GetType().AssemblyQualifiedName, PrefixStyle.Base128);
Serializer.Serialize(stream, packet);

stream.Flush();

This is my server code :

ImageConverter imageConverter = new ImageConverter();
// Wait for client to conncet
var client = new ExtendedTcpClient(listener.AcceptTcpClient());
currentClientControlling = client;

// Deserialize type
var typeName = Serializer.DeserializeWithLengthPrefix<string>(stream, PrefixStyle.Base128);
var type = Type.GetType(typeName);

// Register the type
var model = RuntimeTypeModel.Default;
model.Add(type, true);

// Deserialize the data
var bytes = model.Deserialize(stream, null, type);

var image = (Bitmap)imageConverter.ConvertFrom(bytes);

And this is my Packet model :

public enum PacketType
{
    IMAGE
}

[ProtoContract]
public class Packet<T>
{
    [ProtoMember(1)]
    public PacketType type { get; set; }

    [ProtoMember(2)]
    public T value { get; set; }
}

Solution

  • I didn't figure out what the problem was. However, I solved it by replacing Serializer.Serialize(stream, packet); with Serializer.SerializeWithLengthPrefix(stream, packet, PrefixStyle.Base128);