开发者

transfer int over network

I am new to network programming so I have a qu开发者_开发问答estion: is it safe to send an integer (let's assume 16 bit integer because 32 has issue with "endianess") in my case between C++ and C# and how do that?

In my program I cast int to char (I know is is lower than 255) and send it. However, I would like to send 32 int. I tried conduct that with protocol buffers. I used WriteVarint32 in C++ and ProtoReader.ReadUInt32 in C# with no success (exception in C#). I thought it will work after I read this.

Would you be so kind and suggest me the right way to send an integer between C++ and C# applications? If you explained me how to do that with protocol buffers (protobuf-net in case of C#), I would be very pleased.


Basically it's going to depend on the network libraries that you use and how compatible they are at either end. At the lowest level the data is being transferred as stream or block of bytes. When these bytes are converted back to any more complex structure above a byte (even an int) then the encoding obviously matters and needs to match at both ends.

Easiest thing is just to try it out and see.

It sounds like you might be interested in packing the data as tightly as possible (from your comment on converting ints to chars) in which case maybe you should just write a set of low level packing routines at either end. That way you have no worries over encoding and you can squeeze every last bit out of the packet.


There is no endianess issues with the varint encoding, it's always little endian by design. It stores the value seven bits at a time starting with the least significant seven bits, and uses the eighth bit as stop bit when there is no more one bits left.

You use the Read7BitEncodedInt method in C# to read a varint encoded integer.


If you are writing with protobuf-net, the WithLengthPrefix methods will do this for you. I'd be more than happy to help with this (I'm the author). Btw, the reason it is throwing an exception is that a varint value by itself is not normally valid in a protobuf stream. The system will override this in the case of WithLengthPrefix if you pass 0 as the field number (or pass a positive field-number for a more pure protobuf stream; this is optional, though).

As it happens there is a method on ProtoReader to read an isolated varint (without worrying about protobuf stream semantics) it would be trivial for me to add such to ProtoWriter if that would be useful.

Btw - in terms of PrefixStyle, Base128 is the same as varint. Some folks prefer 32-bit prefixes, to marry up with other systems - hence a few others are provided.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜