我正在编写一个程序,需要通过TCP套接字将数据从客户端发送到服务器。
我有以下代码来序列化和绝望化对象。
public static byte[] serializeObjects(Object obj)
{
using (MemoryStream ms = new MemoryStream()) {
IFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
byte[] bytes = ms.ToArray();
return bytes;
}
}
public static Object deserialiseObject(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream()) {
IFormatter bf = new BinaryFormatter();
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
var obj = bf.Deserialize(ms);
return obj;
}
}
从客户端发送来自服务器的序列化数据的代码。
while ((userInput = Console.ReadLine()) != null)
{
byte[] serialisedObject;
serialisedObject = serializeObjects(userInput);
byte[] userDataBytes = BitConverter.GetBytes((Int32)serialisedObject.Length);
_writer.Write(userDataBytes);
_writer.Write(serialisedObject);
_writer.Flush();
从流中接收序列化数据的代码。
NetworkStream stream = new NetworkStream(socket, true);
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
byte[] readMsgLeng = new byte[4];
stream.Read(readMsgLeng, 0, 4);
int dataLength = BitConverter.ToInt32(readMsgLeng, 0);
byte[] messageData = new byte[dataLength];
stream.Read(messageData, 0, dataLength);
returnedObject = deserialiseObject(messageData);
发生的错误如下所示“输入流不是有效的二进制格式。起始内容(以字节为单位)是:......”
不确定导致错误的是什么。