C#通过socket发送结构对象 [英] C# send structure objects through socket

查看:57
本文介绍了C#通过socket发送结构对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些 C# 客户端/服务器编程方面的内容.我对这个过程非常熟悉,可以提出以下问题:

i have done a bit of reading in client/server programming in c#. i am familiar enough with this process to ask the following question:

如何通过 tcp/ip 而不是字符串传输结构对象?

how do i transmit structure objects through tcp/ip instead of just strings?

我的应用是一款具有聊天功能的网络游戏.因此,不仅仅是传输文本,我想采用一个具有两个字段的数据结构或类结构:i.包类型 ii.数据包类型的数据

my app is a networked game with chat capabilities. so instead of just transmitting text, i would like to imploy a data structure or class structure that will have two fields: i. packet type ii. the data for the packet type

并且我会在应用程序执行期间需要时传输它,并在接收端解码数据对象并将其放置在它所属的位置.

and i would transmit this when needed during the execution of the application, and decode the data object at the receiving end and place it where it belongs.

我不是在寻找代码,只是一些想法和搜索语句,我可以提供给谷歌,所以我会的;有更好的理解.

im not looking for code, just some ideas and search statements i can feed to google so i will; have a better understanding.

我读过关于序列化/反序列化的文章,这是他要走的路吗?

ive read about serialisation/de serialisation, is that he way to go?

谢谢.

我已经检查了显示为相关主题的帖子,但仍需要进一步的指导.

i have checked the posts that showed up as related topics but would still like further guidence.

推荐答案

您可以创建基于 Socket 的 NetworkStream,并使用任何 Stream 机制来传输您的数据.这将您的问题转换为:如何从/向流读取/写入结构.

You can create a NetworkStream based on a Socket, and use any Stream mechanism to transport your data. That translates your question to: How can I read/write a struct from/to a Stream.

您可以使用序列化,也可以使用 BinaryWriter/BinaryReader.对于一个小的结构(如您所描述的),我会编写一些自定义方法:

You can use Serialization but also a BinaryWriter/BinaryReader. For a small struct (like you describe) I would write some custom methods:

var netStream = new NetworkStream(clientSocket, true);
var writer = new BinaryWriter(netStream);

writer.Write(data.Value1);
writer.Write(data.Value2);

对于较大的结构,我会考虑 Cheeso 的 Marshaling 选项.

For larger structures I would consider Cheeso's Marshaling option.

这篇关于C#通过socket发送结构对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆