Advertisement

C# Server isn't reading Java bytes correctly?

Started by August 10, 2015 06:28 AM
15 comments, last by jeskeca 9 years, 3 months ago

OK, this looks like an Endian problem.

The integer 1 is encoded as the bytes [00 00 00 01] in big-endian and [01 00 00 00] in little-endian. But if you read [00 00 00 01] in little endian, you get 16777216.

In other words, it appears Java is writing the integer in big endian mode, and C# is reading in little endian mode. This is what fastcall22 was warning about in his post.

The way I usually deal with this is to make sure that both sides agree on a specific endian to use for the network traffic. I don't know if C# or Java have functions like C's host-to-network and network-to-host functions, but you can define them yourself. In C# you can use BitConverter.IsLittleEndian to determine the endianness of the computer your code is running on, and then decide whether to reverse the byte order when reading/writing data. You can probably do something similar in Java, but I'm not as familiar with it.

Hm, I'll look into it and I'll report back here :) thanks for this heads up.

I checked Java's docs; it says that DataOutputStream will always use big-endian regardless of the processor's native endianness, so you can assume that your network traffic is always big-endian, and then you only need to have endian-specific code on the C# side of things.
Advertisement

I checked Java's docs; it says that DataOutputStream will always use big-endian regardless of the processor's native endianness, so you can assume that your network traffic is always big-endian, and then you only need to have endian-specific code on the C# side of things.

Is there anyway of sending a little-endian bytebuffer through a dataoutputstream to the server?

I don't use Java much, but some other posts online suggest using a ByteBuffer, setting it explicitly into little-endian mode. The following thread is talking about preparing a buffer to write to a file, but you could pass the resulting byte array to the DataOutputStream:

http://stackoverflow.com/questions/1394735/java-writing-in-file-little-endian

I don't use Java much, but some other posts online suggest using a ByteBuffer, setting it explicitly into little-endian mode. The following thread is talking about preparing a buffer to write to a file, but you could pass the resulting byte array to the DataOutputStream:

http://stackoverflow.com/questions/1394735/java-writing-in-file-little-endian

Hm, I'm thinking about just re-writing the server into Java... I didn't really get far on the C# one because of this packet issue. I can't seem to get this to work right

That's a good idea; it'll also let you share common code between client and server as well.
Advertisement
Another option is to use a cross language encoding like thrift, protocol buffers, or even xml.

This topic is closed to new replies.

Advertisement