0

I have a multi-threaded client-server application that uses Vector<String> as a queue of messages to send.

I need, however, to send a file using this application. In C++ I would not really worry, but in Java I'm a little confused when converting anything to string.

Java has 2 byte characters. When you see Java string in HEX, it's usually like:

00XX 00XX 00XX 00XX

Unless some Unicode characters are present.

Java also uses Big endian.

These facts make me unsure, whether - and eventually how - to add the file into the queue. Preferred format of the file would be:

-- Headers --
2 bytes  Size of the block (excluding header, which means first four bytes)
2 bytes  Data type (text message/file)
-- End of headers --
2 bytes  Internal file ID (to avoid referring by filenames)
2 bytes  Length of filename
X bytes  Filename
X bytes  Data

You can see I'm already using 2 bytes for all numbers to avoid some horrible operations required when getting 2 numbers out of one char.

But I have really no idea how to add the file data correctly. For numbers, I assume this would do:

StringBuilder packetData = new StringBuilder();
packetData.append((char) packetSize);
packetData.append((char) PacketType.BINARY.ordinal()); //Just convert enum constant to number

But file is really a problem. If I have also described anything wrongly regarding the Java data types please correct me - I'm a beginner.

Community
  • 1
  • 1

1 Answers1

1

Does it have to send only Strings? I think if it does then you really need to encode it using base64 or similar. The best approach overall would probably be to send it as raw bytes. Depending on how difficult it would be to refactor your code to support byte arrays instead of just Strings, that may be worth doing.

To answer your String question I just saw pop up in the comments, there's a getBytes method on a String.

For the socket question, see: Java sending and receiving file (byte[]) over sockets

Community
  • 1
  • 1
khampson
  • 13,812
  • 4
  • 39
  • 40