最佳实践:在 C# 中为已知协议生成和解析网络数据包?
我尝试询问 最近有类似的问题,但是经过几次回答后,我意识到这不是正确的问题。
是否有基于现有协议(如 SMPP(短消息对等协议 [用于 SMS 消息])或各种聊天协议(如 HOTLINE 或 IRC with C#)生成和解析网络数据包的指南或普遍接受的实践。
其中一个答案提到了 Google Protocol Buffers 和 .NET 版本。看完之后,我意识到如果您可以控制两端(客户端和服务器),那么序列化非常有用。我将遵循协议规范。
生成 过去,我创建了一个类或结构,其属性是网络数据包/协议的一部分:
// PSEUDO CODE
class NetworkObject
{
private int length;
private string data;
// ...
public byte[] GetBytes()
{
// Convert string and int to byte array
return byte array;
}
}
该类有一个 byte[] GetBytes() 方法,我在设置适当的属性后调用该方法。我获取该字节数组并通过网络发送它。在我上一个问题中,答案之一建议将数据存储在内存流或字节流中,这似乎是一个更好的主意。
看来我的字节数组方法可能比将网络流传递给根据类属性直接将数据包数据写入流的方法慢。这就是我可能会做的,除非我在这里错过了一些非常大的东西。
解析 解析时,我使用各种 case 语句来逐步执行各种 PDU,并生成一个填充了适当属性的 NetworkObject,并按照我认为合适的方式处理它。
I tried asking a similar question recently however after several answers I realized it wasn't the correct thing to ask.
Is there a guide or a generally accepted practice for generating and parsing network packets based on an existing protocol like SMPP (Short Message Peer-to-Peer Protocol [Used for SMS Messages]) or various chat protocols like HOTLINE or IRC with C#.
One of the answers mentioned Google Protocol Buffers and a .NET version. After looking at that I realized that serialization is extremely useful if you have control over both ends (client and server). Where I would be following the protocol spec.
Generating
In the past I have made a class or structure with properties that are part of the network packet / protocol:
// PSEUDO CODE
class NetworkObject
{
private int length;
private string data;
// ...
public byte[] GetBytes()
{
// Convert string and int to byte array
return byte array;
}
}
The class has a byte[] GetBytes() method which I call once I've set the appropriate properties. I take that byte array and send it over the network. In my previous question one of the answers suggested storing the data in a memory stream or bytestream which seems like a better idea.
It seems like my byte array method is probably slower than passing a network stream to a method that writes the packet data according to class properties directly to the stream. Which is what I will probably do unless I'm missing something really big here.
Parsing
When parsing I use various case statements to step through the various PDUs and generate a NetworkObject with the appropriate properties populated and do with it as I see fit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不尝试对象的序列化?
Why don't you try Serialization of objects?