C#通过网络序列化和发送 [英] C# Serialize and send over Network

查看:116
本文介绍了C#通过网络序列化和发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想序列化一个类并通过tcp发送它。这没有问题,但是在客户端应用程序中反序列化流时出现异常。

这就是我的代码:

Hi,
I want to serialize a class and send it over tcp. Thats no problem, but I get an exception while deserializing the stream in the client application.
Thats my code:

[Serializable]
internal class SendObj1
{

    public int cmd;
    public string msg;
}

public class SendObj
{
    public int cmd;
    public string msg;
    public byte[] ToByte(int Command)
    {
        SendObj1 obj1 = new SendObj1();
        obj1.cmd = Command;
        XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
        MemoryStream ms = new MemoryStream();
        xs.Serialize(ms, obj1);
        return ms.ToArray();
    }
    public byte[] ToByte(int Command, string Message)
    {
        SendObj1 obj1 = new SendObj1();
        obj1.cmd = Command;
        obj1.msg = Message;
        XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
        MemoryStream ms = new MemoryStream();
        xs.Serialize(ms, obj1);
        return ms.ToArray();
    }
    public SendObj ToObj(byte[] buffer)
    {
        SendObj1 obj = new SendObj1();
        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
            MemoryStream ms = new MemoryStream();
            obj = (SendObj1) xs.Deserialize(ms);
            msg = obj.msg;
            cmd = obj.cmd;
        }
        catch (Exception e)
        {
        }
        return this;
    }

推荐答案

例外情况说未找到根元素。由于您使用的是XmlSerialization,因此需要设置RootNode。更改可序列化类如下所示



The exception says Root Element is not found. Since your are using XmlSerialization you need to set the RootNode. change the serializable class as below

[Serializable]
[XmlRoot]
public class SendObj1
{
    [XmlElement]
    public int cmd = 0;
    [XmlElement]
    public string msg = string.Empty;
}





/ EDIT

反序列化部分不完整,需要传递缓冲区反序列化流之前的内存流



/EDIT
The deserialization part is incomplete, you need to pass the buffer to memory stream before deserialize the stream

XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
MemoryStream ms = new MemoryStream(buffer); // this is missing in your code
obj = (SendObj1) xs.Deserialize(ms);
msg = obj.msg;
cmd = obj.cmd;


这篇关于C#通过网络序列化和发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆