通过套接字发送不同类型的消息
本文关键字:同类型 消息 套接字 | 更新日期: 2023-09-27 18:30:15
我有一个发送不同类型的消息的tcp客户端,我有点困惑如何使其工作。首先,客户端发送一个字符串(转换为 byte[]),工作正常,但随后我尝试发送一个序列化对象,我不知道该怎么做以及如何让服务器理解该消息不是字符串。我尝试发送的对象是RSA算法的公钥
IFormatter formatter=new BinaryFormatter();
formatter.Serialize(client.GetStream(),RSAParameterskeyinfo);
但我不知道如何让服务器理解此消息不是字节[]。
若要使服务器了解他必须计算的对象类型,必须在客户端和服务器之间共享 dll。这里困难的部分是处理此 dll 的版本(当您对要在客户端和服务器之间共享的对象进行更改时,您必须更新每一端的 dll)
然后使用BinaryFormatter
序列化/反序列化对象。首先在客户端使用类似以下内容序列化您的对象:
MyMessage msg = new MyMessage("My custom message")
byte[] data;
using(var ms = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, msg);
data = ms.ToArray();
/*
* Send to stream
*/
}
然后在服务器大小上,您必须像以下那样反序列化它:
/*
* Get the network stream
*/
BinaryFormatter formatter = new BinaryFormatter();
MyMessage msg = (MyMessage) formatter.Deserialize(myStream);
由于它们共享相同的 dll,因此每一方都知道Message
对象。
有关BinaryFormatter
的详细信息,请参阅:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx