套接字和序列化 C# 的问题

编程入门 行业动态 更新时间:2024-10-21 11:34:59
本文介绍了套接字和序列化 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# 的问题

本文发布于:2023-11-11 18:20:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!