本文介绍了套接字和序列化 C# 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实现了一个使用带线程的 Socket 的客户端和服务器模型
I implemented a Client and Server model that uses Socket with thread
当我只想将一个字符串从客户端传递到服务器时,它可以工作.但我想传递一个对象,它抛出这个错误:试图反序列化一个空流"
When I want to pass only a string from Client to the Server, it works. But I want to pass an object and it throws this error: "Attempting to deserialize an empty stream"
代码如下:
ASCIIEncoding asen = new ASCIIEncoding(); MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); Command command = new Command("meuLogin", "minhaSenha"); binaryFormatter.Serialize(memoryStream, command); stream.Write(memoryStream.ToArray(), 0, memoryStream.ToArray().Length);服务器:
byte[] message = new byte[4096]; int bytesRead = 0; bytesRead = clientStream.Read(message, 0, 4096); MemoryStream memoryStream = new MemoryStream(bytesRead); BinaryFormatter bf1 = new BinaryFormatter(); memoryStream.Position = 0; Command command = (Command)bf1.Deserialize(memoryStream);另一个问题:我从 Client 复制了类 Command 并粘贴到 Server 进行反序列化.这是正确的吗?
Another question: I copied the class Command from Client and pasted at Server to deserialize. Is this correct?
谢谢
推荐答案我也推荐 WCF.但是如果你继续使用套接字,你的协议中缺少的关键元素是 消息框架.
I also recommend WCF. But if you continue using sockets, the key element that you're missing in your protocol is message framing.
更多推荐
套接字和序列化 C# 的问题
发布评论