I want to serialize a 'Player' class and send it over my network stream to a client.
Player Class
[ProtoMember(1)]
public int flag;
[ProtoMember(2)]
public Int16 id;
[ProtoMember(3)]
public MyVector3 CharPos;
[ProtoMember(7)]
public bool spawned;
MyVector3
(due to the fact that protobuf does not support serialization of Vector3
)
[ProtoContract]
public class MyVector3
{
[ProtoMember(4)]
public float X { get; set; }
[ProtoMember(5)]
public float Y { get; set; }
[ProtoMember(6)]
public float Z { get; set; }
public MyVector3()
{
this.X = 0.0f;
this.Y = 0.0f;
this.Z = 0.0f;
}
public MyVector3(float x, float y, float z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public static implicit operator Vector3(MyVector3 v)
{
return new Vector3(v.X, v.Y, v.Z);
}
public static implicit operator MyVector3(Vector3 v)
{
return new MyVector3(v.X, v.Y, v.Z);
}
}
Serialize and Deserialize Function
public byte[] serialize(Object obj)
{
if (obj == null)
{
return null;
}
MemoryStream ms = new MemoryStream();
Serializer.SerializeWithLengthPrefix(ms,obj,PrefixStyle.Base128);
return ms.ToArray();
}
public Player deserialize(NetworkStream inc)
{
Player obj = Serializer.DeserializeWithLengthPrefix<Player>(inc,PrefixStyle.Base128);
return obj;
}
Test Function (which in fact does not work!)
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
Serialize ser = new Serialize();
Player temp = new Player();
serverSocket.Start();
while (true)
{
clientSocket = serverSocket.AcceptTcpClient();
using (NetworkStream networkStream = clientSocket.GetStream())
{
DeserializeTest(ser,networkStream);
SerializeTest(ser, networkStream);
}
}
}
static void SerializeTest(Serialize ser,NetworkStream networkStream)
{
Player temp = new Player();
BinaryWriter writer = new BinaryWriter(networkStream);
writer.Write(ser.serialize(temp));
networkStream.Flush();
}
static void DeserializeTest(Serialize ser, NetworkStream networkStream)
{
Player temp = new Player();
temp = (Player)ser.deserialize(networkStream);
Console.WriteLine(temp.flag.ToString() + temp.CharPos.ToString());
networkStream.Flush();
}
}
What now happens:
When the DeserializeTest
is launched, and protobuf tries to deserialize the data from the networkStream
the whole function kind of "Freezes" and starts to loop.
When I'm only serializing the data (in the client) and send it to the server (this code) where its deserialized, everything works like a charm.