从将对象转换为字节数组中获得不同的结果

发布于 2025-02-10 00:34:30 字数 1398 浏览 2 评论 0原文

我正在尝试使用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):

enter image description here

and here is peace of var test on the client-side (note that it has 160 bytes):
enter image description here

why they are different? how I can fix this bug?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文