C# tcp 套接字如何判断正在发送的对象类型?
如果服务器端代码如下所示,如何判断通过套接字发送的对象类型
NetworkStream stream = socket.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream,objectToBeSent);
How to tell what type of object is being sent over a socket if the server side code looks like this
NetworkStream stream = socket.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream,objectToBeSent);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以知道正在发送的对象类型的唯一方法是消息中是否发送了一些元数据来指示它是什么。两个端点都应该知道序列化模式,以便每个端点都可以适当地进行序列化和反序列化。这是(或者应该)您为套接字通信定义的协议的一部分。
The only way you can know what type of object is being sent over is if there is some metadata sent in the message to indicate what it is. The serialization pattern should be known to both endpoints so that each can serialize and unserialize appropriately. This is (or should be) part of the protocol you've defined for your socket communications.
在客户端上,我想您将读取服务器发送的数据并将其反序列化回来:
为此,您显然需要在客户端上包含包含序列化类型的程序集。
哦,请记住 BinaryFormatter 类使用不可互操作的格式。这意味着,如果您在客户端和服务器上使用不同版本的 .NET frmaeowrk,则这可能不起作用。如果是这种情况,您应该使用某种可互操作的数据格式协议在服务器和客户端之间交换信息。
On the client I suppose you are going to read the data sent by the server and deserialize it back:
For this to work you will obviously need to include the assembly containing the serialized type on the client.
Oh and bare in mind that the BinaryFormatter class uses a non-interoperable format. This means that if you use for example different versions of the .NET frmaeowrk on the client and server this might not work. If this is the case you should use some interoperable data format protocol to exchange information between a server and a client.