C# 传递对象 TCPListener
我是 C# 网络编程新手。我发现 TCPListener 类对于在计算机之间发送文本非常有用,但我想知道是否可以在计算机之间直接发送对象(假设客户端和服务器都有类定义),而不必先将它们转换为字符串,然后使具有该数据的对象。
谢谢,
下午
I am new to network programming in C#. I have found the TCPListener class very useful for sending text between computers, but I was wondering if it is possible to directly send objects (assuming both client and server have the class definition) between machines without having to first convert them to string and then make an object with that data.
Thanks,
PM
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决您的问题的一种解决方案是使用 WCF 并将您的对象标记为
Serialized
,并使用 TCP 绑定。但这与您已有的“低级”基于套接字的解决方案有很大不同。不过,我会尝试一下 WCF。One solution for your issue is using WCF and mark your objects as
Serializable
, with TCP binding. But that's quite a different approach than the "low-level", socket based solution you already have. However, I'd give WCF a try.您不能直接通过网络发送“对象”。您必须将它们转换为可解析的二进制或文本形式。对于后者,xml 通常最适合。为此,您可以使用
BinaryFormatter
或XmlSerializer
。如果您确实想发送 .NET 对象,因为您只为 .net 客户端提供服务,则 tcp 可能级别较低,无法满足您的需求。在这种情况下,请查看 .net 远程处理,它允许您直接在服务器和客户端之间交换对象。
You cannot send "objects" directly through the network. You have to either convert them into a parseable binary or text form. For the latter, xml is best suited often. You can use
BinaryFormatter
orXmlSerializer
for this.If you really want to send .NET objects, because you only serve .net clients, tcp may be to low level for your needs. In this case have a look at .net remoting which allows you to directly exchange objects betwen server and client.
只要两侧的类定义相同,您就可以使用二进制序列化将任何对象序列化为流:
不过,您最好如上所述使用 WCF,因为如果程序集在两侧进行版本控制,这将会中断的电线。
As long as the class definitions are the same on both sides, you can use binary serialization to serialize any object to a stream:
You are better off using WCF as noted above, though, since this will break if the assemblies are versioned on either side of the wire.