protobuf是否需要网络数据包头? [英] does protobuf need a network packet header?

查看:115
本文介绍了protobuf是否需要网络数据包头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用TCP的C/S网络程序使用" protobuf ".

I am using 'protobuf' for C/S network program using TCP.

这是我为客户准备的步骤:

here is my steps for client:

1,将数据打包到"protobuf"中

1, pack data into a 'protobuf'

2,获取包大小(以字节为单位)并构建一个长度前缀帧

2, get size in bytes of the pack and construct a length-prefix frame

3,将框架+包写入套接字

3, write the frame+pack to socket

然后是服务器:

1,从套接字读取长度前缀帧,并获得长度N

1, read Length-prefix frame from socket and get the length N

2,从套接字读取N个字节并将数据填充到protobuf实例中

2, read N bytes from socket and fill the data into protobuf instance

3,通过密钥"从protobuf获得值"

3, get "value"s from protobuf by "key"s

我认为这似乎有些复杂,protobuf是否有某种自动生成的长度前缀帧,那么我不需要自己构造一个.或我可以做的其他任何使代码更清洁的事情?

it seems a little complicated I think, is there some kind of auto-generated length-prefix frame for protobuf, then I do not need construct one by myself. or anything else I can do to make code cleaner?

推荐答案

使用protobuf,并假设您沿着同一管道发送多个消息,则:是-您将需要一个长度作为前缀,否则它将想读到流的末尾.

With protobuf, and assuming you are sending multiple messages down the same pipe, then: yes - you will need to have a length as a prefix, otherwise it will want to read to the end of the stream.

protobuf确实包含一些基本的RPC 存根,但是它们使用的RPC实现不是OSS项目的一部分,因此不可用.虽然在实现中列出了一些独立的protobuf RPC堆栈

protobuf does include some basic RPC stubs, but the RPC implementation they use is not part of the OSS project, so that is not available. There are some standalone protobuf RPC stacks listed in the implementations though.

就个人而言,我倾向于假装数据序列是repeated序列的一部分-即,前缀为字段1,字符串"(又名0a),长度为"varint"编码.这意味着整个网络流都是有效的protobuf流.不过,那可能只是我的强迫症发作.

Personally, I tend to pretend that the sequence of data is part of a repeated sequence - i.e. prefix with "field 1, string" (aka 0a), and the length as "varint" encoded. This means that the entire network stream is a valid protobuf stream. That might just be my OCD kicking in, though.

某些实现可能包含一些功能来帮助解决此问题.例如,protobuf-net(.NET版本之一)具有SerializeWithLengthPrefix/DeserializeWithLengthPrefix方法,该方法可以使库为您执行此操作(同时提供多种格式供您选择).

Some implementations may have features included to help with this. protobuf-net (one of the .NET versions) has SerializeWithLengthPrefix/DeserializeWithLengthPrefix methods, for example, which lets the library do this for you (while offering a range of formats for your choosing).

这篇关于protobuf是否需要网络数据包头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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