准备好通过 TCPClient 流发送的序列化对象 [英] Serializing object ready to send over TCPClient Stream

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

问题描述

我已经使用 TcpListenerTcpClient 设置了服务器和客户端.

I've got a server and client set up using TcpListener and TcpClient.

我想将一个对象发送到我的服务器应用程序进行处理.

I want to send an object to my server application for processing.

我发现了 using System.Runtime.Serialization 和以下 文档,但我不想胡说八道,发现我正在用冗长的方式做这件事.

I've discovered the using System.Runtime.Serialization and the following documentation, but I didn't want to faff around to find that I'm doing it in long winded way.

问题:通过 TCP 流处理和发送对象的最佳方法是什么?

The question: What is the best way to process and send an object over the TCP stream?

发送和接收.

以下是我的对象示例:

// Create a new house to send
house newHouse = new house();

// Set variables
newHouse.street = "Mill Lane";
newHouse.postcode = "LO1 BT5";
newHouse.house_number = 11;
newHouse.house_id = 1;
newHouse.house_town = "London";

推荐答案

假设您有一个类 House(在连接的两端都可用),如下所示:

Assuming you have a class House (available on both sides of your connection) looking like this:

[Serializable]
public class House
{
    public string Street { get; set; }
    public string ZipCode { get; set; }
    public int Number { get; set; }
    public int Id { get; set; }
    public string Town { get; set; }
}

您可以将类序列化为 MemoryStream.然后您可以像这样在 TcpClient 连接中使用:

You can serialize the class into a MemoryStream. You can then use in your TcpClient connection like this:

// Create a new house to send house and set values.
var newHouse = new House
    {
        Street = "Mill Lane", 
        ZipCode = "LO1 BT5", 
        Number = 11, 
        Id = 1, 
        Town = "London"
    };  

var xmlSerializer = new XmlSerializer(typeof(House));
var networkStream = tcpClient.GetStream();
if (networkStream.CanWrite)
{
    xmlSerializer.Serialize(networkStream, newHouse);
}

当然,你还得多做一点调查,才能让程序无一例外地运行.(例如,检查 memoryStream.Length 不要大于 int,a.s.o.),但我希望我给了你正确的建议来帮助你;-)

Of course you have to do a little more investigation to make the program running without exception. (e.g. Check memoryStream.Length not to be greater than an int, a.s.o.), but I hope I gave you the right suggestions to help you on your way ;-)

这篇关于准备好通过 TCPClient 流发送的序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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