title: Send and receive byte[] in server-client TCP application
body: <p>I need to send and receive bytes in from my client to server over NetworkStream. I know how to communicate with strings, but now I need to send and receive bytes.</p>
  
  <p>For example, something like that:</p>
  
  <pre><code>static byte[] Receive(NetworkStream netstr)
  {
      try
      {
          byte[] recv = new Byte[256];
  
          int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
          return recv;
      }
      catch (Exception ex)
      {
          Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
  
          return null;
      }
  
  
  
  }
  
  static void Send(NetworkStream netstr, byte[] message)
  {
      try
      {
          netstr.Write(message, 0, message.Length);
      }
      catch (Exception ex)
      {
          Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
      }
  }
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>        private void prejmi_click(object sender, EventArgs e)
          {
              const string IP = "127.0.0.1";
              const ushort PORT = 54321;
              TcpListener listener = new TcpListener(IPAddress.Parse(IP), PORT);
              listener.Start();
              TcpClient client = listener.AcceptTcpClient();
              NetworkStream ns = client.GetStream();
  
              byte[] data = Receive(ns)
  
  }
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>        private void poslji_Click(object sender, EventArgs e)
          {
              const string IP = "127.0.0.1";
              const ushort PORT = 54321;
  
              TcpClient client = new TcpClient();
              client.Connect(IP, PORT);
  
              string test="hello";
              byte[] mybyte=Encoding.UTF8.GetBytes(test);
              Send(ns,mybyte);
  }
  </code></pre>
  
  <p>But that is not the propper way to do this, because byte[] data on server side will always have length of 256.</p>