我正在尝试使用socket传输一个texture2D。 我正面临一些序列化问题。
这是我用来序列化texture2D的方法:
Texture2D tex = new Texture2D(5, 5);
bool loaded = tex.LoadImage(File.ReadAllBytes(Environment.CurrentDirectory + "/Assets/Textures/IMG_3122.jpg"));
tex.Apply();
byte[] bytes = tex.EncodeToPNG();
NetworkWriter writer = new NetworkWriter();
writer.WriteBytesFull(bytes);
byte[] data = writer.AsArray();
byte error;
byte[] buffer = new byte[1024];
int bufferSize = 1024;
Stream stream = new MemoryStream();
stream.Write(data, 0, 1024);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, data);
Debug.Log("Send byte : " + connectionId);
NetworkTransport.Send(socketId, connectionId, myReliableChannelId, buffer, bufferSize, out error);
对于接收方,这是代码:
switch (recNetworkEvent)
{
case NetworkEventType.Nothing:
break;
case NetworkEventType.ConnectEvent:
Debug.Log("New Connection event received");
break;
case NetworkEventType.DataEvent:
Stream stream = new MemoryStream();
stream.Read(recBuffer, 0, bufferSize);
//deserialize
BinaryFormatter formatter = new BinaryFormatter();
string receivedImgBase64 = formatter.Deserialize(stream) as string;
//convert received base64 string to bytearray for texture display
byte[] imgByteArray = Encoding.ASCII.GetBytes(receivedImgBase64);
}
因此,当我尝试读取接收方的recBuffer
时,流为空。
错误:
SerializationException:serializationStream支持搜索,但其长度为0
这是序列化过程中的错误还是别的什么?
答案 0 :(得分:0)
Stream.Read(Byte[], Int32, Int32)
从流中读取字节并将其放入recBuffer
。但是你刚刚分配了流,所以它是空的 - 没有什么可读的。
您可能想要使用this constructor:
Stream stream = new MemoryStream(recBuffer, 0, bufferSize);