简体   繁体   中英

Java send floatbuffer over a tcp socket efficiently

I am relatively new to socket programming in java and want to send data from a Floatbuffer variable over a tcp socket. This should run on an android platform.

Here's some code to illustrate what I want to do:

FloatBuffer buf = FloatBuffer.allocate(4);
buf.put(5.5f);
buf.put(1.5f);
buf.put(2.5f);
buf.put(3.5f);

ServerSocket server = new ServerSocket(38300);
con = server.accept();

// somehow send the whole buf variable over the tcp socket

I am sure you can extract each float and individually send them over the socket, but I wonder if there is a more efficient way to do so?

How about creating a backing ByteBuffer for it. That way you have plenty of choices on how to transmit the data over the network. With a SocketChannel you'll get it as simple as this.

ByteBuffer buf = ByteBuffer.allocate(floats*4);
FloatBuffer floats = buf.asFloatBuffer();
floats.put(5.5f);
...
ServerSocket server = new ServerSocket(38300);
SocketChannel sc = server.accept().getChannel();
sc.write(buf);

The most efficient solution in terms of quantity of data sent over the network is sending the float directly.

Every float is 32 bit lengths and is not possible to reduce it if you needs to send float.

An alternative, not always applicable, is to send less bits using a different type .

For example instead of sending

5.5f
1.5f
2.5f
3.5f

why don't multiply them by 10 and send only byte or short primitives?

On the other side of the socket you can reconstruct the float dividing the byte (or short) by 10.0

For this kind of solution you can save 4x (for byte) or 2x (for short) in terms of bits sent over the network .

Note: you can apply this solution if you know that the range of possible data is restrict to same known values . As an example sending values between 0 to 10 with 1 decimal digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM