title: JAVA - Working with a custom socket protocol
body: <p>I'm trying to connect via sockets with a C application which expects a certain header and data body, however, I'm getting a bunch of issues when trying to comply with that format, it should be like this:</p>
  
  <p>Header:<br>
  - 2 bytes for packet start.<br>
  - 4 bytes that indicate the packet size plus header.<br>
  - 1 byte for packet type.   </p>
  
  <p>Body:<br>
  - 4 bytes that indicate quantity of params.  </p>
  
  <p>One block of the following for each parameter:<br>
  - 4 bytes for parameter longitude.<br>
  - X Bytes for message content.<br>
  - 1 byte for escape char.  </p>
  
  <p>Here's an example of what the server is expecting:</p>
  
  <p>[%%][13 00 00 00][0][12 00 00 00][0b 00 00 00][OPERATIONPERFORMED\0] </p>
  
  <p>The problem I'm having is that when trying to send the information via PrintWriter, the other end is getting the hex values as ASCII chars instead of an actual value. 
  I've already tried with ByteBuffer, DataOutputStream and several options, but still they're coming out in that format or even weirder.</p>
  
  <p>From what I'm investigating it seems the endian is inverted, so they get the right bytes but in the wrong order.</p>
  
  <p>The implementation I'm trying now is the following:</p>
  
  <pre><code>  DataOutputStream stream = new DataOutputStream(socket.getOutputStream());
      PrintWriter writer = new PrintWriter(socket.getOutputStream()); 
  
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
      // Header
      stream.writeChar(37);
      stream.writeChar(37); 
      stream.writeInt(26);
      stream.writeChar('\\0');
  
      stream.writeInt(1);
      stream.writeInt(11);
  
      stream.writeUTF("SET_PROBLE\\0");
  
  
      stream.flush();
  
      StringBuilder sb = new StringBuilder();
  
      boolean state = true;
  
      while (state) {
          if (in.ready()) {
              sb.append((char) in.read());
          }
          else {
              if (sb.length() &gt; 0) {
                  state = false;
              }
          }
      }
  
      System.out.println(sb.toString().trim());
  
  }
  </code></pre>
  
  <p>Can you help me out?</p>
  
  <p>Thanks a lot in advance!</p>