从将对象转换为字节数组中获得不同的结果
我正在尝试使用asp.net core和websockets创建一个使者。我希望客户端将message
对象转换为byte []
,然后通过一个Websocket。但是在服务器端,我无法将客户端序列化的对象进行化。经过一些调试后,我发现两侧相同对象的序列化缓冲区之间存在一些差异。 actully,从msg
在服务器端上的serialized byte []
与serialized byte []
从msg不相同
客户端上的对象。
这是我在服务器端上的代码:
Message msg = new Message()
{
Text="Test"
};
var test = ObjectToByteArray(msg);
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
[Serializable]
public class Message
{
public string Text { get; set; }
}
客户端上的代码完全相同(我的服务器端是ASP.NET Core 5 API,我的客户端是Avalonia dotnet 6)
,但这是的和平
var test
在服务器端(请注意,它具有170个字节):
,这是客户端上的var test
的和平(请注意它有160个字节):
为什么它们有所不同?我如何解决此错误?
I am trying to create a messenger using asp.net core and WebSockets.I want the client to convert a Message
object to byte[]
and send it to the server by a WebSocket. But on the server-side, I can't deserialize the object that the client serialized. after some debugging, I found some differences between serialized buffers from the same objects on both sides.
actully, the serialized byte[]
from msg
object on the server-side is not the same as serialized byte[]
from msg
object on the client-side.
Here is my code on the server-side:
Message msg = new Message()
{
Text="Test"
};
var test = ObjectToByteArray(msg);
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
[Serializable]
public class Message
{
public string Text { get; set; }
}
And exactly the same code on the client-side (my server-side is asp.net core 5 API and my client-side is Avalonia dotnet 6)
but here is peace of var test
on the server-side (note that it has 170 bytes):
and here is peace of var test
on the client-side (note that it has 160 bytes):
why they are different? how I can fix this bug?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论