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

查看:136
本文介绍了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?

我的应用程序与聊天功能的联网游戏。所以,而不只是传输的文字,我想imploy数据结构或类结构,将有两个字段:我。包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.

我不是找代码,只是一些想法和搜索语句,我可以提交给Google所以我会;有一个更好的了解。

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.


推荐答案

您可以创建一个的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的封送处理选项。

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

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

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