[英]Is it possible to detect message type in protobuf-csharp-port?
A java client constructs a Message according to this skeleton : Java客户端根据以下框架构造Message:
package tutorial;
option java_package = "com.example.sff.piki2";
option java_outer_classname = "MsgProtos";
message MSG {
required string guid = 1;
required int32 MsgCode = 2;
required int32 From = 3; //sender
...
This message is sent to a C# program ( server side). 该消息发送到C#程序(服务器端)。
The server knows how to read the bytes ( first byte is the number of bytes to read which represents the size of the following message ). 服务器知道如何读取字节( 第一个字节是要读取的字节数,代表接下来的消息的大小 )。
This is how MSG is being constructed by a byte array. 这就是字节数组构造MSG的方式。
MSG Msg = MSG.CreateBuilder().MergeFrom(buffer).Build();
Where buffer is the byte array which read from the socket. 其中buffer是从套接字读取的字节数组。
But now I'm in a situation where a client needs to send "Heartbeat" message( another message) in order to check if the server is alive or not. 但是现在我处于一种情况,客户端需要发送“ Heartbeat”消息( 另一条消息)以检查服务器是否处于活动状态。 ( the server should respond : "yes i'm alive" )
(服务器应响应: “是,我还活着” )
Sure , I can add another field to the MSG
class. 当然,我可以在
MSG
类中添加另一个字段。 but I don't want to because the MSG
class has a lot of unnecessary fields - for a Heartbeat operation. 但我不想这样做,因为
MSG
类具有很多不必要的字段-用于心跳操作。
Question : 题 :
The server read n bytes. 服务器读取了n个字节。 Is there anyway I can know if this is a
MSG
message or a "Heartbeat" message ? 无论如何,我是否可以知道这是
MSG
消息还是“ Heartbeat”消息?
Is there anyway I can know if this is a MSG message or a "Heartbeat" message?
无论如何,我是否可以知道这是MSG消息还是“ Heartbeat”消息?
No. Protocol buffer messages don't contain any such type information. 不会。协议缓冲区消息不包含任何此类类型信息。 Typically the way round this is to have a "wrapper" type with a field for each message you might want to send.
通常,解决方法是使用“包装器”类型,并为您可能要发送的每条消息添加一个字段。 You'd ideally want to express this as a
oneof
, but my port doesn't support that (yet). 理想情况下,您希望将其表示为
oneof
,但我的港口还不支持。
The overhead is minimal - but it will be a protocol change, of course, so you'll need to think about any existing servers etc. 开销是最小的-当然,这将是协议的更改,因此您需要考虑任何现有服务器等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.