将浮点数从.NET发送到Java并返回的最佳方法

EMP*_*EMP 7 .net java serialization

我正在编写一个.NET应用程序,它将对Java应用程序进行RPC调用(通过消息队列).在两个方向上发送的数据将是大型浮点数组.序列化它们以通过网络发送它们的最佳方法是什么?我想要比文本更紧凑的东西,但是与架构无关,因为服务器可能不是x86机器.可以根据需要更改Java应用程序.

Kev*_*ock 6

Java数字原语实际上存储(在JVM中)并以网络顺序写入(通过jnava.io.DataOutputStreamjava.nio.ByteBuffer),浮点值是IEEE标准.它们可以直接与C#/ .NET互换.好吧,如果.NET提供网络字节顺序来读取双精度数(请参阅下面的代码).

因此,只要.NET端按照您应该始终使用的网络字节顺序读/写,就可以使用此处提到的两个类(以及输入对应项)发送和接收任何原语.

Java方面例如:

// Assume the following somewhere in your class
Socket socket;
DataOutputStream out = new DataOutputStream(socket.getOutputStream());

// Send a double
out.writeDouble(doubleValue);
Run Code Online (Sandbox Code Playgroud)

C#端检索值:

Stream stream = new NetworkStream(socket, FileAccess.ReadWrite, true);
BinaryReader reader = new BinaryReader(stream, Encoding.UTF8);   

// Read double from the stream
long v = IPAddress.NetworkToHostOrder(reader.ReadInt64());   
double doubleValue = BitConverter.Int64BitsToDouble(v);
Run Code Online (Sandbox Code Playgroud)

对于写入你做相反的事情,C#必须以网络字节顺序写入.

Stream stream = new NetworkStream(socket, FileAccess.ReadWrite, true);
BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8);

// Write double to the stream
long v = BitConverter.DoubleToInt64Bits(doubleValue);
writer.Write(IPAddress.HostToNetworkOrder(v));
Run Code Online (Sandbox Code Playgroud)

然后在Java端阅读这些:

// Some where in your class
Socket socket;
DataInputStream in = new DataInputStream(socket.getInputStream());

// To read the double
double doubleValue = in.readDouble();
Run Code Online (Sandbox Code Playgroud)

C#IPAddress类为除double和float之外的所有基元提供网络字节顺序读/写方法,但在我的示例中,您可以分别通过32位或64位int.