0

I am using a Java socket program to write integers and characters from the server back to the client

    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

I want to write an int32 and a char of 8B on the wire. For the integer when I write

    out.printf("%04x",1);

it appears on the wireshark as "30 30 30 31", whereas I want it to appear "01 00 00 00". Similarly for out.printf("%d",1); it appears as "31" whereas I want it "01 00 00 00". How can I write on the wire an integer of 4B and a character of 8B? Does the representation has to do with encoding?

Ioannis Pappas
  • 807
  • 12
  • 22

3 Answers3

2

Using PrintWrite to write text to a socket is not ideal as it will hide any errors.

In your case you appear to want to write binary in so I would suggest you try.

DataOutputStream out = new DataOutputStream(
                       new BufferedOutputStream(clientSocket.getOutputStream()));

out.writeInt(1);

However if you want to sue little endian format, I would use blocking NIO.

SocketChannel sc = 
ByteBuffer bb= ByteBuffer.allocateDirect(1024).order(ByteOrder.LITTLE_ENDIAN);

bb.putInt(1);
// put whatever else
bb.flip();
while(bb.remaining() > 0) sc.write(bb);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I understand the benefits of DataOutputStream. However for some reason neither writeInt(1) nor writeUTF("Peter") are printed. If I remove the BufferedOutputStream then they are written. Any idea why this happens? Moreover, I am interested in sending an int32 and char[8] with one call, i.e. concatenated in a single PDU e.g. with a payload "01 00 00 00 AA AA AA AA" – Ioannis Pappas Aug 08 '12 at 14:28
  • You need to flush the stream to push the data. If you take out BufferedOutputStream it will be slower, but you won't have to flush the data. If you want to combine the int32 and the char[] then you want to be buffering the data and then flush after the `char[]` – Peter Lawrey Aug 08 '12 at 14:34
  • BTW: You can't assume that because you sent the int32 and char[] together that you won't get a) only a portion of this data in one read(), b) multiple "message" in one read() c) some combination of a and b – Peter Lawrey Aug 08 '12 at 14:35
1

Yes. By specifying "%04x" and the String conversion, you implicitly select Hexdecimal encoding for your data (i.e. convert the number into an ASCII String).

Use a ByteBuffer instead to convert the integer into four bytes. See this answer for details.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

If you want to write binary data, don't use PrintWriter or any other Writer as a wrapper. Try using DataOutputStream instead, which provides a set of methods for writing ints and so on.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108