简体   繁体   中英

Java TCP/IP socket send byte-aligned data

I am having a hard time sending byte-aligned data over a socket because the examples I've been following use a PrintWriter class which converts everything to a string representation.

I want to send 3 float values, with a header and a footer. This way the consumer knows exactly how many bytes to read per transmission. My client sends something like the following:

//Add a header:
float type = params[0];
if (type == TransmitService.ACC_TYPE) out.print('a');
else if (type == TransmitService.GYR_TYPE) out.print('g');
else out.print('u'); //unknown - wtf? hasn't happened yet but just in case

//Payload:
out.print(params[1]);
out.print(params[2]);
out.print(params[3]);

//Footer:
out.print('e');

Here is the initialization of network objects:

echoSocket = new Socket(HOST, PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);

Then on the server side I want to do something like read exactly 26 bytes at a time (8 bytes per 3 floats on a 64-bit system, 1 byte for header char, 1 byte for footer char). The exact number doesn't matter, I can test and figure that out.

What's problematic is that out.print() converts everything to a string, so if I have 0.001000.. with trailing zeros, it will truncate to 0.001 as a string, which is 5 chars, giving me inconsistent byte transaction amounts for my server.

It's in MATLAB unfortunately and doing the following:

t=tcpip('0.0.0.0', 8000, 'NetworkRole', 'server');
fopen(t);

bytesToRead = 26;
data = fread(t,bytesToRead);

What should I do to consistently send my header, 3 floats, and footer to my server?

Cheers

So don't use a PrintWriter. Use a DataOutputStream. It has methods for sending floats and all other primitives.

'Byte-aligned' has nothing to do with it. All data is byte-aligned.

You shouldn't use PrintWriter, I believe.

Try using eg an ObjectOutputStream.

http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html

With this one you can write bytes, chars, floats, basically
anything (including primitive types and objects).
And you don't go through a String, you write binary data.

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