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
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Perhaps you can base64-encode the file's binary representation. – Matt Ball May 23 '14 at 01:49
  • Unfortunately, base64 significantly increases file size. Something you want to avoid when sending files over network. – Tomáš Zato May 23 '14 at 01:51
  • The answer is *yes, but you really shouldn't*. If sending files is a new requirement, then reworking the queue system to either be more flexible in message type or handle the files out of band is in order. – chrylis -cautiouslyoptimistic- May 23 '14 at 01:57
  • That might be true, however the queue system is not here to decide what data is what. So all I can do is to abbadon this question and post question: *How to convert string into a byte array* and *How to send a byte array through socket*. – Tomáš Zato May 23 '14 at 01:59

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
  • 14,700
  • 4
  • 41
  • 43