通过tcp类 [英] Class though tcp

查看:74
本文介绍了通过tcp类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我整天都试图通过tcp发送一个类:我试图将它转换为字节数组(使用Marshal)然后发送它但是只发送它适用于最琐碎的案件;数据到达正常,但是当我尝试将其转换回来时会出现致命错误,也就是当我在我的类中使用ArrayLists-s时,如果我使用简单数组然后我得到另一种类型的异常,就像运行时类型那样t适合子类类型;


如果在客户端和服务器上单独测试,则从类到字节数组的转换有效。所有字节接缝都被服务器接收。


我还剩下两个选项:通过文件发送信息或者把它全部放在一个大的...(使它成为一个huuuge字符串)并添加一些奇怪的分隔符。 


有人可以帮我吗?

解决方案

您可以在一端序列化数据并在另一端反序列化它。只要发送者和接收者都知道这些类型(当然它们是可序列化的),你就可以实现你所追求的目标。


有几种方法可以序列化一个类:最有效的方法之一是通过 BinaryFormatter 。或者,您也可以使用 XmlSerializer 。有一些事情需要考虑,但这通常只需要很少的编码。


您可能要考虑的另一种方法是改为使用Web服务:在这种情况下所有传输并自动处理您的数据序列化。这可能证明不如自定义解决方案灵活,但结果代码具有高可读性和可维护性。


HTH
--mc


 


Hi,

I was trying all day to send a class through tcp: I tried to convert it to a byte array(using Marshal) then send it but that only works for the most trivial case; the data arrives alright but it gives a fatal error when I try to convert it back, that is when I use ArrayLists-s in my class, if I use simple arrays then I get another type of exception, something like the runtime type doesn't fit the the subclass type;

The conversion from a class to an array of bytes works if tested separately on the client and on the server. All bytes seam to get received by the server.

I just have two more options left: send the information through a file or put it all in a big... (make that a huuuge string) and add some weird separators. 

Can someone help me with this?

解决方案

You could serialize your data on one end and deserialize it on the other end. As long as the types are known by both the sender and the receiver (and they are serializable, of course), you can then achieve what you are after.

There are several ways to serialize a class: one of the most efficient way is by means of BinaryFormatter. Alternatively, you could also use an XmlSerializer. There are a few things to take into account, but this usually requires very little coding.

Another approach you may want to consider is to use a Web service instead: in that case all the transmission and serialization of your data is handled automatically. This may prove to be less flexible than a custom solution, but the resulting code is highly readable and maintainable.

HTH
--mc

 


这篇关于通过tcp类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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