title: Google Multiplayer RealTime socket streams
body: <p>I wonder if someone used RealTime sockets with Google Multiplayer (rather than messages).</p>
  
  <p>I have a code that works OK with streams derived from  "native"(IP) socket, so I expected it to work with RealTime socket streams too. Unfortunately this is not the case.</p>
  
  <p>The following code works fine with RealTime sockets</p>
  
  <pre><code>Sending end:
      int s1, s2;
      os.write(new byte[] {(byte)s1, (byte)s2};
      os.flush();    // May be redundant, according to Google docs
  Receiving end:
      byte[] buffer = new byte[2];
      is.read(buffer);
      int r1=buffer[0] &amp; 0xff;
      int r2=buffer[1] &amp; 0xff;
  </code></pre>
  
  <p>However, since the length of chuck is unknown in advance, I prefer to spit the chunk into two pieces: length and the data, read one after another. Consider therefore a different code:</p>
  
  <pre><code>Sending end:
      byte s1, s2;
      os.write(s1);
      os.write(s2);
      os.flush();
  Receiving end:
      int r1=is.read();
      int r2=is.read();
  </code></pre>
  
  <p>In this case, only first byte is read, while the second byte never comes!</p>
  
  <p>Since Android docs don't recommend flush, I tried to make a wrapper for caching several writes into one on flush:</p>
  
  <pre><code>public class OutputStreamWrapper extends OutputStream {
      private OutputStream innerOs;
      private ByteArrayOutputStream baos;
  
      public OutputStreamWrapper(OutputStream innerOs) {
          this.innerOs = innerOs;
          baos = new ByteArrayOutputStream();
      }
  
      @Override
      public void write(int oneByte) throws IOException {
          baos.write(oneByte);
      }
  
  
      @Override
      public void flush() throws IOException {
          if (baos.size() &gt; 0) 
              innerOs.write(baos.toByteArray());
          baos.reset();
      }
  
      @Override
      public void write(byte[] buffer, int offset, int count)
          throws IOException {
          baos.write(buffer, offset, count);
      }
  
  
      @Override
      public void close() throws IOException {
          flush();
          innerOs.close();
          baos.close();
      }
  }
  </code></pre>
  
  <p>The problem persists!</p>
  
  <p>Am I doing something wrong?</p>
  
  <p>If I can't find the solution, I will have to write custom streams as wrappers for Real-Time Messages, but it is really a shame to avoid "ready to use" streams.</p>