You're reading from end of memory stream:
MemoryStream rms = new MemoryStream(1024);
rms.Write (...);
// Now cursor is at end of file, nothing to read here
t = (T) xs.Deserialize(rms);
Just move cursor back to beginning before you deserialize:
rms.Seek(0, SeekOrigin.Begin);
t = (T) xs.Deserialize(rms); // Now deserializer has data to read
Finally just two small suggestions. Don't forget to dispose all disposable objects:
MemoryStream rms = new MemoryStream(1024);
{
}
Also you don't need to read a byte of stream into a string (decoding UTF8) then getting bytes back (from UTF8), this double conversion adds nothing (moreover please note you encode twice because you call GetBytes()
twice):
if (recievedData.Length > 0)
{
using (MemoryStream rms = new MemoryStream(receivedData))
{
t = (T) xs.Deserialize(rms);
}
}
For logging purposes you can write a function like this (UTF8 conversion will be done only if necessary):
static class Logger
{
[Conditional("DEBUG")]
public static void Debug(Func<string> text)
{
Debug.Log(text());
}
}
Your logging will be (and it'll be called only if DEBUG
symbol is defined):
Logger.Debug(() => "ms: " + Encoding.UTF8.GetString(rms.ToArray()));
It's just a more pretty alternative to:
#if DEBUG
Debug.Log ("ms: " + System.Text.Encoding.UTF8.GetString(rms.ToArray()));
#endif