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

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

问题描述

我有一个服务器和客户端设置使用的TcpListener 的TcpClient



我要发送对象为处理我的服务器应用程序。



我发现了使用系统.Runtime.Serialization 及以下文档。,但我不想faff四处打听,我做它长篇大论方式



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



发送和接收。



这里是一个比如我的对象:

  //创建一个新的房子送
家纽豪斯=新房子();

//设置变量
newHouse.street =米尔巷;
newHouse.postcode =LO1 BT5
newHouse.house_number = 11;
newHouse.house_id = 1;
newHouse.house_town =伦敦;


解决方案

假设你有一个类众议院(在您连接的双方提供)看起来像这样:

  [Serializable接口] 
公共类房子
{
公共字符串街{搞定;组; }
公共字符串邮编{搞定;组; }
公众诠释号码{搞定;组; }
公众诠释标识{搞定;组; }
公共字符串镇{搞定;组; }
}

您可以序列化类成 MemoryStream的。然后,您可以在这样的的TcpClient 连接使用:

  //创建一个新的房子送房子和设定值。 
变种纽豪斯=新房
{
街=米尔巷,
邮政编码=LO1 BT5,
数= 11,
n = 1,
镇=伦敦
};

XmlSerializer的VAR =新的XmlSerializer(typeof运算(楼));
变种的NetworkStream = tcpClient.GetStream();
如果(networkStream.CanWrite)$ B $乙:{
xmlSerializer.Serialize(的NetworkStream,纽豪斯);
}



当然,你必须做一些更多的研究,以使程序运行不例外。 (例如检查 memoryStream.Length 不超过一个int更大,ASO),但我希望我给你正确的建议,以帮助你的方式; - )


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.

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.

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

Sending and receiving.

Here's an example of my object:

// 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";

解决方案

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; }
}

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);
}

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天全站免登陆