title: Sockets - getting and setting size of the receiving packet
body: <p>I've seen different approach on this one.
  I have a server written in java and c# client.</p>
  
  <p>Most of the data sending examples I've seen data is simply sent using:</p>
  
  <p><strong>Sent from C# client</strong></p>
  
  <pre><code>TcpClient tcpClient = _tcpClient.Connect(ip, port);
  NetworkStream stream = _tcpClient.GetStream();
  BinaryWriter s = new BinaryWriter(stream);
  
  //send some info
  byte[] bytes = new byte[]{1,2,3}
  
  //capsulated in thread
      s.Write(bytes);
      s.Flush();
  </code></pre>
  
  <p>And on received</p>
  
  <p><strong>Received on Java server</strong></p>
  
  <pre><code>Socket socket = // create it on incoming connection
  DataInputStream input = new DataInputStream(socket.getInputStream());
  
  //we create some magical size byte array
  byte[] bytes = new byte[4096];
  input.read(bytes);
  </code></pre>
  
  <p>The problem is that magical size byte array doesn't really look like a solid solution. I hate creating thing which I cant control or don't know the content of.
  So solution I came up with is sending the byte array size first</p>
  
  <pre><code>s.Write(bytes.length); //send int or byte array of the int value
  s.Flush();
  s.Write(bytes);
  s.Flush();
  </code></pre>
  
  <p>and on receive</p>
  
  <pre><code>int size = input.readInt();
  byte[] bytes = new byte[size];
  input.read(bytes);
  </code></pre>
  
  <p>So now I have byte array which all content is completely filled.</p>
  
  <p>I don't know why, but I have also doubts about this solution, must be because ive seen examples with first solution only. What do you think about second solution, are or might there be any problems with it you could see, maybe there are better solutions?</p>